.NET2 handling of exceptions in ThreadPool threads
[mono.git] / mono / metadata / threadpool.c
1 /*
2  * threadpool.c: global thread pool
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Gonzalo Paniagua Javier (gonzalo@ximian.com)
7  *
8  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9  * Copyright 2004-2010 Novell, Inc (http://www.novell.com)
10  */
11
12 #include <config.h>
13 #include <glib.h>
14
15 #ifdef MONO_SMALL_CONFIG
16 #define QUEUE_LENGTH 16 /* Must be 2^N */
17 #else
18 #define QUEUE_LENGTH 64 /* Must be 2^N */
19 #endif
20
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/tabledefs.h>
23 #include <mono/metadata/threads.h>
24 #include <mono/metadata/threads-types.h>
25 #include <mono/metadata/threadpool-internals.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/file-io.h>
28 #include <mono/metadata/monitor.h>
29 #include <mono/metadata/mono-mlist.h>
30 #include <mono/metadata/marshal.h>
31 #include <mono/metadata/mono-perfcounters.h>
32 #include <mono/metadata/socket-io.h>
33 #include <mono/metadata/mono-wsq.h>
34 #include <mono/io-layer/io-layer.h>
35 #include <mono/metadata/gc-internal.h>
36 #include <mono/utils/mono-time.h>
37 #include <mono/utils/mono-proclib.h>
38 #include <mono/utils/mono-semaphore.h>
39 #include <errno.h>
40 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #include <sys/types.h>
44 #include <fcntl.h>
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #include <string.h>
49 #ifdef HAVE_SYS_SOCKET_H
50 #include <sys/socket.h>
51 #endif
52 #include <mono/utils/mono-poll.h>
53 #ifdef HAVE_EPOLL
54 #include <sys/epoll.h>
55 #endif
56
57 #ifndef DISABLE_SOCKETS
58 #include "mono/io-layer/socket-wrappers.h"
59 #endif
60
61 #include "threadpool.h"
62
63 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
64                                                 ThreadState_SuspendRequested)) != 0)
65
66 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
67 #define SPIN_LOCK(i) do { \
68                                 if (SPIN_TRYLOCK (i)) \
69                                         break; \
70                         } while (1)
71
72 #define SPIN_UNLOCK(i) i = 0
73
74 #define EPOLL_DEBUG(...)
75 #define EPOLL_DEBUG_STMT(...)
76 #define TP_DEBUG(...)
77 #define TP_DEBUG_STMT(...)
78
79 /* DEBUG: prints tp data every 2s */
80 #undef DEBUG 
81
82 /*
83 #define EPOLL_DEBUG(...) g_message(__VA_ARGS__)
84 #define EPOLL_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
85 #define TP_DEBUG(...) g_message(__VA_ARGS__)
86 #define TP_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
87 */
88
89 /* map of CounterSample.cs */
90 struct _MonoCounterSample {
91         gint64 rawValue;
92         gint64 baseValue;
93         gint64 counterFrequency;
94         gint64 systemFrequency;
95         gint64 timeStamp;
96         gint64 timeStamp100nSec;
97         gint64 counterTimeStamp;
98         int counterType;
99 };
100
101 /* mono_thread_pool_init called */
102 static volatile int tp_inited;
103
104 typedef struct {
105         CRITICAL_SECTION io_lock; /* access to sock_to_state */
106         int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
107         int pipe [2];
108         MonoGHashTable *sock_to_state;
109
110         HANDLE new_sem; /* access to newpfd and write side of the pipe */
111         mono_pollfd *newpfd;
112         gboolean epoll_disabled;
113 #ifdef HAVE_EPOLL
114         int epollfd;
115 #endif
116 } SocketIOData;
117
118 static SocketIOData socket_io_data;
119
120 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
121 typedef struct {
122         MonoObject         object;
123         MonoMethodMessage *msg;
124         MonoMethod        *cb_method;
125         MonoDelegate      *cb_target;
126         MonoObject        *state;
127         MonoObject        *res;
128         MonoArray         *out_args;
129 } ASyncCall;
130
131 typedef struct {
132         MonoSemType lock;
133         MonoMList *first; /* GC root */
134         MonoMList *last;
135         MonoMList *unused; /* Up to 20 chunks. GC root */
136         gint head;
137         gint tail;
138         MonoSemType new_job;
139         volatile gint waiting; /* threads waiting for a work item */
140
141         /**/
142         volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
143         /* min, max, n and busy -> Interlocked */
144         volatile gint min_threads;
145         volatile gint max_threads;
146         volatile gint nthreads;
147         volatile gint busy_threads;
148
149         void (*async_invoke) (gpointer data);
150         void *pc_nitems; /* Performance counter for total number of items in added */
151         void *pc_nthreads; /* Performance counter for total number of active threads */
152         /**/
153         volatile gint destroy_thread;
154         volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
155         volatile gint sp_lock; /* spin lock used to protect ignore_times */
156         volatile gint64 last_check;
157         volatile gint64 time_sum;
158         volatile gint n_sum;
159         gint64 averages [2];
160         /**/
161         //TP_DEBUG_ONLY (gint nodes_created);
162         //TP_DEBUG_ONLY (gint nodes_reused);
163         gboolean is_io;
164 } ThreadPool;
165
166 static ThreadPool async_tp;
167 static ThreadPool async_io_tp;
168
169 static void async_invoke_thread (gpointer data);
170 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
171 static void threadpool_free_queue (ThreadPool *tp);
172 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
173 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
174 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
175 static void threadpool_start_idle_threads (ThreadPool *tp);
176 static void threadpool_kill_idle_threads (ThreadPool *tp);
177 static gboolean threadpool_start_thread (ThreadPool *tp);
178 static void monitor_thread (gpointer data);
179
180 static MonoClass *async_call_klass;
181 static MonoClass *socket_async_call_klass;
182 static MonoClass *process_async_call_klass;
183
184 static GPtrArray *wsqs;
185 CRITICAL_SECTION wsqs_lock;
186
187 /* Hooks */
188 static MonoThreadPoolFunc tp_start_func;
189 static MonoThreadPoolFunc tp_finish_func;
190 static gpointer tp_hooks_user_data;
191 static MonoThreadPoolItemFunc tp_item_begin_func;
192 static MonoThreadPoolItemFunc tp_item_end_func;
193 static gpointer tp_item_user_data;
194
195 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
196 enum {
197         AIO_OP_FIRST,
198         AIO_OP_ACCEPT = 0,
199         AIO_OP_CONNECT,
200         AIO_OP_RECEIVE,
201         AIO_OP_RECEIVEFROM,
202         AIO_OP_SEND,
203         AIO_OP_SENDTO,
204         AIO_OP_RECV_JUST_CALLBACK,
205         AIO_OP_SEND_JUST_CALLBACK,
206         AIO_OP_READPIPE,
207         AIO_OP_LAST
208 };
209
210 #ifdef DISABLE_SOCKETS
211
212 #define socket_io_cleanup(x)
213
214 static int
215 get_event_from_state (MonoSocketAsyncResult *state)
216 {
217         g_assert_not_reached ();
218         return -1;
219 }
220
221 static int
222 get_events_from_list (MonoMList *list)
223 {
224         return 0;
225 }
226
227 #else
228
229 static void
230 socket_io_cleanup (SocketIOData *data)
231 {
232         EnterCriticalSection (&data->io_lock);
233         if (data->inited != 2) {
234                 LeaveCriticalSection (&data->io_lock);
235                 return;
236         }
237         data->inited = 3;
238
239 #ifdef HOST_WIN32
240         closesocket (data->pipe [0]);
241         closesocket (data->pipe [1]);
242 #else
243         if (data->pipe [0] > -1)
244                 close (data->pipe [0]);
245         if (data->pipe [1] > -1)
246                 close (data->pipe [1]);
247 #endif
248         data->pipe [0] = -1;
249         data->pipe [1] = -1;
250         if (data->new_sem)
251                 CloseHandle (data->new_sem);
252         data->new_sem = NULL;
253         mono_g_hash_table_destroy (data->sock_to_state);
254         data->sock_to_state = NULL;
255         g_free (data->newpfd);
256         data->newpfd = NULL;
257 #ifdef HAVE_EPOLL
258         if (FALSE == data->epoll_disabled)
259                 close (data->epollfd);
260 #endif
261         LeaveCriticalSection (&data->io_lock);
262 }
263
264 static int
265 get_event_from_state (MonoSocketAsyncResult *state)
266 {
267         switch (state->operation) {
268         case AIO_OP_ACCEPT:
269         case AIO_OP_RECEIVE:
270         case AIO_OP_RECV_JUST_CALLBACK:
271         case AIO_OP_RECEIVEFROM:
272         case AIO_OP_READPIPE:
273                 return MONO_POLLIN;
274         case AIO_OP_SEND:
275         case AIO_OP_SEND_JUST_CALLBACK:
276         case AIO_OP_SENDTO:
277         case AIO_OP_CONNECT:
278                 return MONO_POLLOUT;
279         default: /* Should never happen */
280                 g_message ("get_event_from_state: unknown value in switch!!!");
281                 return 0;
282         }
283 }
284
285 static int
286 get_events_from_list (MonoMList *list)
287 {
288         MonoSocketAsyncResult *state;
289         int events = 0;
290
291         while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
292                 events |= get_event_from_state (state);
293                 list = mono_mlist_next (list);
294         }
295
296         return events;
297 }
298
299 #define ICALL_RECV(x)   ves_icall_System_Net_Sockets_Socket_Receive_internal (\
300                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
301                                  x->socket_flags, &x->error);
302
303 #define ICALL_SEND(x)   ves_icall_System_Net_Sockets_Socket_Send_internal (\
304                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
305                                  x->socket_flags, &x->error);
306
307 #endif /* !DISABLE_SOCKETS */
308
309 static void
310 threadpool_jobs_inc (MonoObject *obj)
311 {
312         if (obj)
313                 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
314 }
315
316 static gboolean
317 threadpool_jobs_dec (MonoObject *obj)
318 {
319         MonoDomain *domain = obj->vtable->domain;
320         int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
321         if (remaining_jobs == 0 && domain->cleanup_semaphore) {
322                 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
323                 return TRUE;
324         }
325         return FALSE;
326 }
327
328 #ifdef HAVE_EPOLL
329 static MonoObject *
330 get_io_event (MonoMList **list, gint event)
331 {
332         MonoObject *state;
333         MonoMList *current;
334         MonoMList *prev;
335
336         current = *list;
337         prev = NULL;
338         state = NULL;
339         while (current) {
340                 state = mono_mlist_get_data (current);
341                 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
342                         break;
343
344                 state = NULL;
345                 prev = current;
346                 current = mono_mlist_next (current);
347         }
348
349         if (current) {
350                 if (prev) {
351                         mono_mlist_set_next (prev, mono_mlist_next (current));
352                 } else {
353                         *list = mono_mlist_next (*list);
354                 }
355         }
356
357         return state;
358 }
359 #endif
360
361 static MonoMList *
362 process_io_event (MonoMList *list, int event)
363 {
364         MonoSocketAsyncResult *state;
365         MonoMList *oldlist;
366
367         oldlist = list;
368         state = NULL;
369         while (list) {
370                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
371                 if (get_event_from_state (state) == event)
372                         break;
373                 
374                 list = mono_mlist_next (list);
375         }
376
377         if (list != NULL) {
378                 oldlist = mono_mlist_remove_item (oldlist, list);
379                 EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
380                 threadpool_append_job (&async_io_tp, (MonoObject *) state);
381         }
382
383         return oldlist;
384 }
385
386 static int
387 mark_bad_fds (mono_pollfd *pfds, int nfds)
388 {
389         int i, ret;
390         mono_pollfd *pfd;
391         int count = 0;
392
393         for (i = 0; i < nfds; i++) {
394                 pfd = &pfds [i];
395                 if (pfd->fd == -1)
396                         continue;
397
398                 ret = mono_poll (pfd, 1, 0);
399                 if (ret == -1 && errno == EBADF) {
400                         pfd->revents |= MONO_POLLNVAL;
401                         count++;
402                 } else if (ret == 1) {
403                         count++;
404                 }
405         }
406
407         return count;
408 }
409
410 static void
411 socket_io_poll_main (gpointer p)
412 {
413 #if MONO_SMALL_CONFIG
414 #define INITIAL_POLLFD_SIZE     128
415 #else
416 #define INITIAL_POLLFD_SIZE     1024
417 #endif
418 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
419         SocketIOData *data = p;
420         mono_pollfd *pfds;
421         gint maxfd = 1;
422         gint allocated;
423         gint i;
424         MonoInternalThread *thread;
425
426         thread = mono_thread_internal_current ();
427
428         allocated = INITIAL_POLLFD_SIZE;
429         pfds = g_new0 (mono_pollfd, allocated);
430         INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
431         for (i = 1; i < allocated; i++)
432                 INIT_POLLFD (&pfds [i], -1, 0);
433
434         while (1) {
435                 int nsock = 0;
436                 mono_pollfd *pfd;
437                 char one [1];
438                 MonoMList *list;
439
440                 do {
441                         if (nsock == -1) {
442                                 if (THREAD_WANTS_A_BREAK (thread))
443                                         mono_thread_interruption_checkpoint ();
444                         }
445
446                         nsock = mono_poll (pfds, maxfd, -1);
447                 } while (nsock == -1 && errno == EINTR);
448
449                 /* 
450                  * Apart from EINTR, we only check EBADF, for the rest:
451                  *  EINVAL: mono_poll() 'protects' us from descriptor
452                  *      numbers above the limit if using select() by marking
453                  *      then as MONO_POLLERR.  If a system poll() is being
454                  *      used, the number of descriptor we're passing will not
455                  *      be over sysconf(_SC_OPEN_MAX), as the error would have
456                  *      happened when opening.
457                  *
458                  *  EFAULT: we own the memory pointed by pfds.
459                  *  ENOMEM: we're doomed anyway
460                  *
461                  */
462
463                 if (nsock == -1 && errno == EBADF) {
464                         pfds->revents = 0; /* Just in case... */
465                         nsock = mark_bad_fds (pfds, maxfd);
466                 }
467
468                 if ((pfds->revents & POLL_ERRORS) != 0) {
469                         /* We're supposed to die now, as the pipe has been closed */
470                         g_free (pfds);
471                         socket_io_cleanup (data);
472                         return;
473                 }
474
475                 /* Got a new socket */
476                 if ((pfds->revents & MONO_POLLIN) != 0) {
477                         int nread;
478
479                         for (i = 1; i < allocated; i++) {
480                                 pfd = &pfds [i];
481                                 if (pfd->fd == -1 || data->newpfd == NULL ||
482                                         pfd->fd == data->newpfd->fd)
483                                         break;
484                         }
485
486                         if (i == allocated) {
487                                 mono_pollfd *oldfd;
488
489                                 oldfd = pfds;
490                                 i = allocated;
491                                 allocated = allocated * 2;
492                                 pfds = g_renew (mono_pollfd, oldfd, allocated);
493                                 g_free (oldfd);
494                                 for (; i < allocated; i++)
495                                         INIT_POLLFD (&pfds [i], -1, 0);
496                         }
497 #ifndef HOST_WIN32
498                         nread = read (data->pipe [0], one, 1);
499 #else
500                         nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
501 #endif
502                         if (nread <= 0) {
503                                 g_free (pfds);
504                                 return; /* we're closed */
505                         }
506
507                         INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
508                         ReleaseSemaphore (data->new_sem, 1, NULL);
509                         if (i >= maxfd)
510                                 maxfd = i + 1;
511                         nsock--;
512                 }
513
514                 if (nsock == 0)
515                         continue;
516
517                 EnterCriticalSection (&data->io_lock);
518                 if (data->inited == 3) {
519                         g_free (pfds);
520                         LeaveCriticalSection (&data->io_lock);
521                         return; /* cleanup called */
522                 }
523
524                 for (i = 1; i < maxfd && nsock > 0; i++) {
525                         pfd = &pfds [i];
526                         if (pfd->fd == -1 || pfd->revents == 0)
527                                 continue;
528
529                         nsock--;
530                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
531                         if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
532                                 list = process_io_event (list, MONO_POLLIN);
533                         }
534
535                         if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
536                                 list = process_io_event (list, MONO_POLLOUT);
537                         }
538
539                         if (list != NULL) {
540                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
541                                 pfd->events = get_events_from_list (list);
542                         } else {
543                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
544                                 pfd->fd = -1;
545                                 if (i == maxfd - 1)
546                                         maxfd--;
547                         }
548                 }
549                 LeaveCriticalSection (&data->io_lock);
550         }
551 }
552
553 #ifdef HAVE_EPOLL
554 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
555 #define EPOLL_NEVENTS   128
556 static void
557 socket_io_epoll_main (gpointer p)
558 {
559         SocketIOData *data;
560         int epollfd;
561         MonoInternalThread *thread;
562         struct epoll_event *events, *evt;
563         int ready = 0, i;
564         gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
565         gint nresults;
566
567         data = p;
568         epollfd = data->epollfd;
569         thread = mono_thread_internal_current ();
570         events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
571
572         while (1) {
573                 do {
574                         if (ready == -1) {
575                                 if (THREAD_WANTS_A_BREAK (thread))
576                                         mono_thread_interruption_checkpoint ();
577                         }
578                         EPOLL_DEBUG ("epoll_wait init");
579                         ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
580                         EPOLL_DEBUG_STMT(
581                                 int err = errno;
582                                 EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
583                                 errno = err;
584                         );
585                 } while (ready == -1 && errno == EINTR);
586
587                 if (ready == -1) {
588                         int err = errno;
589                         g_free (events);
590                         if (err != EBADF)
591                                 g_warning ("epoll_wait: %d %s", err, g_strerror (err));
592
593                         close (epollfd);
594                         return;
595                 }
596
597                 EnterCriticalSection (&data->io_lock);
598                 if (data->inited == 3) {
599                         g_free (events);
600                         close (epollfd);
601                         LeaveCriticalSection (&data->io_lock);
602                         return; /* cleanup called */
603                 }
604
605                 nresults = 0;
606                 for (i = 0; i < ready; i++) {
607                         int fd;
608                         MonoMList *list;
609                         MonoObject *ares;
610
611                         evt = &events [i];
612                         fd = evt->data.fd;
613                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
614                         EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
615                         if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
616                                 ares = get_io_event (&list, MONO_POLLIN);
617                                 if (ares != NULL)
618                                         async_results [nresults++] = ares;
619                         }
620
621                         if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
622                                 ares = get_io_event (&list, MONO_POLLOUT);
623                                 if (ares != NULL)
624                                         async_results [nresults++] = ares;
625                         }
626
627                         if (list != NULL) {
628                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
629                                 evt->events = get_events_from_list (list);
630                                 EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
631                                 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
632                                         if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
633                                                 EPOLL_DEBUG_STMT (
634                                                         int err = errno;
635                                                         EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
636                                                         errno = err;
637                                                 );
638                                         }
639                                 }
640                         } else {
641                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
642                                 EPOLL_DEBUG ("DEL %d", fd);
643                                 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
644                         }
645                 }
646                 LeaveCriticalSection (&data->io_lock);
647                 threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
648                 memset (async_results, 0, sizeof (gpointer) * nresults);
649         }
650 }
651 #undef EPOLL_NEVENTS
652 #endif
653
654 /*
655  * select/poll wake up when a socket is closed, but epoll just removes
656  * the socket from its internal list without notification.
657  */
658 void
659 mono_thread_pool_remove_socket (int sock)
660 {
661         MonoMList *list, *next;
662         MonoSocketAsyncResult *state;
663
664         if (socket_io_data.inited == 0)
665                 return;
666
667         EnterCriticalSection (&socket_io_data.io_lock);
668         if (socket_io_data.sock_to_state == NULL) {
669                 LeaveCriticalSection (&socket_io_data.io_lock);
670                 return;
671         }
672         list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
673         if (list)
674                 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
675         LeaveCriticalSection (&socket_io_data.io_lock);
676         
677         while (list) {
678                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
679                 if (state->operation == AIO_OP_RECEIVE)
680                         state->operation = AIO_OP_RECV_JUST_CALLBACK;
681                 else if (state->operation == AIO_OP_SEND)
682                         state->operation = AIO_OP_SEND_JUST_CALLBACK;
683
684                 next = mono_mlist_remove_item (list, list);
685                 list = process_io_event (list, MONO_POLLIN);
686                 if (list)
687                         process_io_event (list, MONO_POLLOUT);
688
689                 list = next;
690         }
691 }
692
693 #ifdef HOST_WIN32
694 static void
695 connect_hack (gpointer x)
696 {
697         struct sockaddr_in *addr = (struct sockaddr_in *) x;
698         int count = 0;
699
700         while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
701                 Sleep (500);
702                 if (++count > 3) {
703                         g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
704                         g_assert (WSAGetLastError ());
705                 }
706         }
707 }
708 #endif
709
710 static void
711 socket_io_init (SocketIOData *data)
712 {
713 #ifdef HOST_WIN32
714         struct sockaddr_in server;
715         struct sockaddr_in client;
716         SOCKET srv;
717         int len;
718 #endif
719         int inited;
720         guint32 stack_size;
721
722         if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
723                 return;
724
725         inited = InterlockedCompareExchange (&data->inited, 1, 0);
726         if (inited >= 1) {
727                 while (TRUE) {
728                         if (data->inited >= 2)
729                                 return;
730                         SleepEx (1, FALSE);
731                 }
732         }
733
734         EnterCriticalSection (&data->io_lock);
735
736 #ifdef HAVE_EPOLL
737         data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
738         if (FALSE == data->epoll_disabled) {
739                 data->epollfd = epoll_create (256);
740                 data->epoll_disabled = (data->epollfd == -1);
741                 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
742                         g_message ("epoll_create() failed. Using plain poll().");
743         } else {
744                 data->epollfd = -1;
745         }
746 #else
747         data->epoll_disabled = TRUE;
748 #endif
749
750 #ifndef HOST_WIN32
751         if (data->epoll_disabled) {
752                 if (pipe (data->pipe) != 0) {
753                         int err = errno;
754                         perror ("mono");
755                         g_assert (err);
756                 }
757         } else {
758                 data->pipe [0] = -1;
759                 data->pipe [1] = -1;
760         }
761 #else
762         srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
763         g_assert (srv != INVALID_SOCKET);
764         data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
765         g_assert (data->pipe [1] != INVALID_SOCKET);
766
767         server.sin_family = AF_INET;
768         server.sin_addr.s_addr = inet_addr ("127.0.0.1");
769         server.sin_port = 0;
770         if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
771                 g_print ("%d\n", WSAGetLastError ());
772                 g_assert (1 != 0);
773         }
774
775         len = sizeof (server);
776         getsockname (srv, (SOCKADDR *) &server, &len);
777         listen (srv, 1);
778         mono_thread_create (mono_get_root_domain (), connect_hack, &server);
779         len = sizeof (server);
780         data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
781         g_assert (data->pipe [0] != INVALID_SOCKET);
782         closesocket (srv);
783 #endif
784         data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
785
786         if (data->epoll_disabled) {
787                 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
788                 g_assert (data->new_sem != NULL);
789         }
790
791         stack_size = mono_threads_get_default_stacksize ();
792         mono_threads_set_default_stacksize (128 * 1024);
793         if (data->epoll_disabled) {
794                 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
795         }
796 #ifdef HAVE_EPOLL
797         else {
798                 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
799         }
800 #endif
801         mono_threads_set_default_stacksize (stack_size);
802         LeaveCriticalSection (&data->io_lock);
803         data->inited = 2;
804 }
805
806 static void
807 socket_io_add_poll (MonoSocketAsyncResult *state)
808 {
809         int events;
810         char msg [1];
811         MonoMList *list;
812         SocketIOData *data = &socket_io_data;
813         int w;
814
815         if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
816                 return;
817
818 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
819         /* select() for connect() does not work well on the Mac. Bug #75436. */
820         /* Bug #77637 for the BSD 6 case */
821         /* Bug #78888 for the Windows case */
822         if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
823                 //FIXME: increment number of threads while this one is waiting?
824                 threadpool_append_job (&async_io_tp, (MonoObject *) state);
825                 return;
826         }
827 #endif
828         WaitForSingleObject (data->new_sem, INFINITE);
829         if (data->newpfd == NULL)
830                 data->newpfd = g_new0 (mono_pollfd, 1);
831
832         EnterCriticalSection (&data->io_lock);
833         if (data->sock_to_state == NULL) {
834                 LeaveCriticalSection (&data->io_lock);
835                 return;
836         }
837
838         /* FIXME: 64 bit issue: handle can be a pointer on windows? */
839         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
840         if (list == NULL) {
841                 list = mono_mlist_alloc ((MonoObject*)state);
842         } else {
843                 list = mono_mlist_append (list, (MonoObject*)state);
844         }
845
846         events = get_events_from_list (list);
847         INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
848         mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
849         LeaveCriticalSection (&data->io_lock);
850         *msg = (char) state->operation;
851 #ifndef HOST_WIN32
852         w = write (data->pipe [1], msg, 1);
853         w = w;
854 #else
855         send ((SOCKET) data->pipe [1], msg, 1, 0);
856 #endif
857 }
858
859 #ifdef HAVE_EPOLL
860 static gboolean
861 socket_io_add_epoll (MonoSocketAsyncResult *state)
862 {
863         MonoMList *list;
864         SocketIOData *data = &socket_io_data;
865         struct epoll_event event;
866         int epoll_op, ievt;
867         int fd;
868
869         if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
870                 return TRUE;
871
872         memset (&event, 0, sizeof (struct epoll_event));
873         fd = GPOINTER_TO_INT (state->handle);
874         EnterCriticalSection (&data->io_lock);
875         if (data->sock_to_state == NULL) {
876                 LeaveCriticalSection (&data->io_lock);
877                 return TRUE;
878         }
879         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
880         if (list == NULL) {
881                 list = mono_mlist_alloc ((MonoObject*)state);
882                 epoll_op = EPOLL_CTL_ADD;
883         } else {
884                 list = mono_mlist_append (list, (MonoObject*)state);
885                 epoll_op = EPOLL_CTL_MOD;
886         }
887
888         ievt = get_events_from_list (list);
889         if ((ievt & MONO_POLLIN) != 0)
890                 event.events |= EPOLLIN;
891         if ((ievt & MONO_POLLOUT) != 0)
892                 event.events |= EPOLLOUT;
893
894         mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
895         event.data.fd = fd;
896         EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
897         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
898                 int err = errno;
899                 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
900                         epoll_op = EPOLL_CTL_MOD;
901                         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
902                                 g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
903                         }
904                 }
905         }
906         LeaveCriticalSection (&data->io_lock);
907
908         return TRUE;
909 }
910 #endif
911
912 static void
913 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
914 {
915         if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
916                 return;
917
918         socket_io_init (&socket_io_data);
919
920         MONO_OBJECT_SETREF (state, ares, ares);
921 #ifdef HAVE_EPOLL
922         if (socket_io_data.epoll_disabled == FALSE) {
923                 if (socket_io_add_epoll (state))
924                         return;
925         }
926 #endif
927         socket_io_add_poll (state);
928 }
929
930 #ifndef DISABLE_SOCKETS
931 static gboolean
932 socket_io_filter (MonoObject *target, MonoObject *state)
933 {
934         gint op;
935         MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
936         MonoClass *klass;
937
938         if (target == NULL || state == NULL)
939                 return FALSE;
940
941         if (socket_async_call_klass == NULL) {
942                 klass = target->vtable->klass;
943                 /* Check if it's SocketAsyncCall in System.Net.Sockets
944                  * FIXME: check the assembly is signed correctly for extra care
945                  */
946                 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0 
947                                 && strcmp (mono_image_get_name (klass->image), "System") == 0
948                                 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
949                         socket_async_call_klass = klass;
950         }
951
952         if (process_async_call_klass == NULL) {
953                 klass = target->vtable->klass;
954                 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
955                  * FIXME: check the assembly is signed correctly for extra care
956                  */
957                 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0 
958                                 && strcmp (mono_image_get_name (klass->image), "System") == 0
959                                 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
960                         process_async_call_klass = klass;
961         }
962         /* return both when socket_async_call_klass has not been seen yet and when
963          * the object is not an instance of the class.
964          */
965         if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
966                 return FALSE;
967
968         op = sock_res->operation;
969         if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
970                 return FALSE;
971
972         return TRUE;
973 }
974 #endif /* !DISABLE_SOCKETS */
975
976 /* Returns the exception thrown when invoking, if any */
977 static MonoObject *
978 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
979 {
980         ASyncCall *ac = (ASyncCall *)ares->object_data;
981         MonoObject *res, *exc = NULL;
982         MonoArray *out_args = NULL;
983         HANDLE wait_event = NULL;
984
985         if (ares->execution_context) {
986                 /* use captured ExecutionContext (if available) */
987                 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
988                 mono_thread_set_execution_context (ares->execution_context);
989         } else {
990                 ares->original_context = NULL;
991         }
992
993         if (ac == NULL) {
994                 /* Fast path from ThreadPool.*QueueUserWorkItem */
995                 void *pa = ares->async_state;
996                 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
997         } else {
998                 MonoObject *cb_exc = NULL;
999
1000                 ac->msg->exc = NULL;
1001                 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
1002                 MONO_OBJECT_SETREF (ac, res, res);
1003                 MONO_OBJECT_SETREF (ac, msg->exc, exc);
1004                 MONO_OBJECT_SETREF (ac, out_args, out_args);
1005
1006                 mono_monitor_enter ((MonoObject *) ares);
1007                 ares->completed = 1;
1008                 if (ares->handle != NULL)
1009                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1010                 mono_monitor_exit ((MonoObject *) ares);
1011                 /* notify listeners */
1012                 if (wait_event != NULL)
1013                         SetEvent (wait_event);
1014
1015                 /* call async callback if cb_method != null*/
1016                 if (ac != NULL && ac->cb_method) {
1017                         void *pa = &ares;
1018                         cb_exc = NULL;
1019                         mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
1020                         MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
1021                         exc = cb_exc;
1022                 } else {
1023                         exc = NULL;
1024                 }
1025         }
1026
1027         /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1028         if (ares->original_context) {
1029                 mono_thread_set_execution_context (ares->original_context);
1030                 ares->original_context = NULL;
1031         }
1032         return exc;
1033 }
1034
1035 static void
1036 threadpool_start_idle_threads (ThreadPool *tp)
1037 {
1038         int n;
1039
1040         if (tp->pool_status == 1 && !tp->is_io)
1041                 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, tp, TRUE);
1042         do {
1043                 while (1) {
1044                         n = tp->nthreads;
1045                         if (n >= tp->min_threads)
1046                                 return;
1047                         if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
1048                                 break;
1049                 }
1050                 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1051                 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1052                 SleepEx (100, TRUE);
1053         } while (1);
1054 }
1055
1056 static void
1057 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1058 {
1059         memset (tp, 0, sizeof (ThreadPool));
1060         MONO_SEM_INIT (&tp->lock, 1);
1061         tp->min_threads = min_threads;
1062         tp->max_threads = max_threads;
1063         tp->async_invoke = async_invoke;
1064         MONO_SEM_INIT (&tp->new_job, 0);
1065 }
1066
1067 static void *
1068 init_perf_counter (const char *category, const char *counter)
1069 {
1070         MonoString *category_str;
1071         MonoString *counter_str;
1072         MonoString *machine;
1073         MonoDomain *root;
1074         MonoBoolean custom;
1075         int type;
1076
1077         if (category == NULL || counter == NULL)
1078                 return NULL;
1079         root = mono_get_root_domain ();
1080         category_str = mono_string_new (root, category);
1081         counter_str = mono_string_new (root, counter);
1082         machine = mono_string_new (root, ".");
1083         return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1084 }
1085
1086 #ifdef DEBUG
1087 static void
1088 print_pool_info (ThreadPool *tp)
1089 {
1090
1091 //      if (tp->tail - tp->head == 0)
1092 //              return;
1093
1094         g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
1095         g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
1096         g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
1097         g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
1098         g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
1099         g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
1100         g_print ("Queued: %d\n", (tp->tail - tp->head));
1101         if (tp == &async_tp) {
1102                 int i;
1103                 EnterCriticalSection (&wsqs_lock);
1104                 for (i = 0; i < wsqs->len; i++) {
1105                         g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
1106                 }
1107                 LeaveCriticalSection (&wsqs_lock);
1108         } else {
1109                 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
1110         }
1111         g_print ("-------------\n");
1112 }
1113
1114 static void
1115 signal_handler (int signo)
1116 {
1117         ThreadPool *tp;
1118
1119         tp = &async_tp;
1120         MONO_SEM_WAIT (&tp->lock);
1121         g_print ("\n-----Non-IO-----\n");
1122         print_pool_info (tp);
1123         MONO_SEM_POST (&tp->lock);
1124         tp = &async_io_tp;
1125         MONO_SEM_WAIT (&tp->lock);
1126         g_print ("\n-----IO-----\n");
1127         print_pool_info (tp);
1128         MONO_SEM_POST (&tp->lock);
1129         alarm (2);
1130 }
1131 #endif
1132
1133 static void
1134 monitor_thread (gpointer data)
1135 {
1136         ThreadPool *tp;
1137         MonoInternalThread *thread;
1138         guint32 ms;
1139         gboolean need_one;
1140         int i;
1141
1142         tp = data;
1143         thread = mono_thread_internal_current ();
1144         while (1) {
1145                 ms = 500;
1146                 do {
1147                         guint32 ts;
1148                         ts = mono_msec_ticks ();
1149                         if (SleepEx (ms, TRUE) == 0)
1150                                 break;
1151                         ms -= (mono_msec_ticks () - ts);
1152                         if (mono_runtime_is_shutting_down ())
1153                                 break;
1154                         if (THREAD_WANTS_A_BREAK (thread))
1155                                 mono_thread_interruption_checkpoint ();
1156                 } while (ms > 0);
1157
1158                 if (mono_runtime_is_shutting_down ())
1159                         break;
1160                 if (tp->waiting > 0)
1161                         continue;
1162                 MONO_SEM_WAIT (&tp->lock);
1163                 need_one = (tp->head != tp->tail);
1164                 if (!need_one) {
1165                         EnterCriticalSection (&wsqs_lock);
1166                         for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1167                                 MonoWSQ *wsq;
1168                                 wsq = g_ptr_array_index (wsqs, i);
1169                                 if (mono_wsq_count (wsq) > 0) {
1170                                         need_one = TRUE;
1171                                         break;
1172                                 }
1173                         }
1174                         LeaveCriticalSection (&wsqs_lock);
1175                 }
1176                 MONO_SEM_POST (&tp->lock);
1177                 if (need_one)
1178                         threadpool_start_thread (tp);
1179         }
1180 }
1181
1182 void
1183 mono_thread_pool_init ()
1184 {
1185         gint threads_per_cpu = 1;
1186         gint thread_count;
1187         gint cpu_count = mono_cpu_count ();
1188         int result;
1189
1190         if (tp_inited == 2)
1191                 return;
1192
1193         result = InterlockedCompareExchange (&tp_inited, 1, 0);
1194         if (result == 1) {
1195                 while (1) {
1196                         SleepEx (1, FALSE);
1197                         if (tp_inited == 2)
1198                                 return;
1199                 }
1200         }
1201
1202         MONO_GC_REGISTER_ROOT (async_tp.first);
1203         MONO_GC_REGISTER_ROOT (async_tp.last);
1204         MONO_GC_REGISTER_ROOT (async_tp.unused);
1205         MONO_GC_REGISTER_ROOT (async_io_tp.first);
1206         MONO_GC_REGISTER_ROOT (async_io_tp.unused);
1207         MONO_GC_REGISTER_ROOT (async_io_tp.last);
1208
1209         MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
1210         InitializeCriticalSection (&socket_io_data.io_lock);
1211         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1212                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1213                 if (threads_per_cpu < 1)
1214                         threads_per_cpu = 1;
1215         }
1216
1217         thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1218         threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1219         threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1220         async_io_tp.is_io = TRUE;
1221
1222         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1223         g_assert (async_call_klass);
1224
1225         InitializeCriticalSection (&wsqs_lock);
1226         wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1227         mono_wsq_init ();
1228
1229         async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1230         g_assert (async_tp.pc_nitems);
1231
1232         async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1233         g_assert (async_io_tp.pc_nitems);
1234
1235         async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1236         g_assert (async_tp.pc_nthreads);
1237
1238         async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1239         g_assert (async_io_tp.pc_nthreads);
1240         tp_inited = 2;
1241 #ifdef DEBUG
1242         signal (SIGALRM, signal_handler);
1243         alarm (2);
1244 #endif
1245 }
1246
1247 MonoAsyncResult *
1248 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1249                       MonoObject *state)
1250 {
1251         MonoDomain *domain = mono_domain_get ();
1252         MonoAsyncResult *ares;
1253         ASyncCall *ac;
1254
1255         ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1256         MONO_OBJECT_SETREF (ac, msg, msg);
1257         MONO_OBJECT_SETREF (ac, state, state);
1258
1259         if (async_callback) {
1260                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1261                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1262         }
1263
1264         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1265         MONO_OBJECT_SETREF (ares, async_delegate, target);
1266
1267 #ifndef DISABLE_SOCKETS
1268         if (socket_io_filter (target, state)) {
1269                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1270                 return ares;
1271         }
1272 #endif
1273         threadpool_append_job (&async_tp, (MonoObject *) ares);
1274         return ares;
1275 }
1276
1277 MonoObject *
1278 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1279 {
1280         ASyncCall *ac;
1281         HANDLE wait_event;
1282
1283         *exc = NULL;
1284         *out_args = NULL;
1285
1286         /* check if already finished */
1287         mono_monitor_enter ((MonoObject *) ares);
1288         
1289         if (ares->endinvoke_called) {
1290                 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1291                 mono_monitor_exit ((MonoObject *) ares);
1292                 return NULL;
1293         }
1294
1295         ares->endinvoke_called = 1;
1296         /* wait until we are really finished */
1297         if (!ares->completed) {
1298                 if (ares->handle == NULL) {
1299                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1300                         g_assert(wait_event != 0);
1301                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1302                 } else {
1303                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1304                 }
1305                 mono_monitor_exit ((MonoObject *) ares);
1306                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1307         } else {
1308                 mono_monitor_exit ((MonoObject *) ares);
1309         }
1310
1311         ac = (ASyncCall *) ares->object_data;
1312         g_assert (ac != NULL);
1313         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1314         *out_args = ac->out_args;
1315
1316         return ac->res;
1317 }
1318
1319 static void
1320 threadpool_kill_idle_threads (ThreadPool *tp)
1321 {
1322         gint n;
1323
1324         n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1325         while (n) {
1326                 n--;
1327                 MONO_SEM_POST (&tp->new_job);
1328         }
1329 }
1330
1331 void
1332 mono_thread_pool_cleanup (void)
1333 {
1334         if (async_tp.pool_status == 0 || async_tp.pool_status == 2)
1335                 return;
1336
1337         if (async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)
1338                 return;
1339
1340         InterlockedExchange (&async_io_tp.pool_status, 2);
1341         MONO_SEM_WAIT (&async_tp.lock);
1342         threadpool_free_queue (&async_tp);
1343         threadpool_kill_idle_threads (&async_tp);
1344         MONO_SEM_POST (&async_tp.lock);
1345
1346         socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1347         MONO_SEM_WAIT (&async_io_tp.lock);
1348         threadpool_free_queue (&async_io_tp);
1349         threadpool_kill_idle_threads (&async_io_tp);
1350         MONO_SEM_POST (&async_io_tp.lock);
1351         MONO_SEM_DESTROY (&async_io_tp.new_job);
1352
1353         EnterCriticalSection (&wsqs_lock);
1354         mono_wsq_cleanup ();
1355         if (wsqs)
1356                 g_ptr_array_free (wsqs, TRUE);
1357         wsqs = NULL;
1358         LeaveCriticalSection (&wsqs_lock);
1359         MONO_SEM_DESTROY (&async_tp.new_job);
1360 }
1361
1362 /* Caller must enter &tp->lock */
1363 static MonoObject*
1364 dequeue_job_nolock (ThreadPool *tp)
1365 {
1366         MonoObject *ar;
1367         MonoArray *array;
1368         MonoMList *list;
1369
1370         list = tp->first;
1371         do {
1372                 if (mono_runtime_is_shutting_down ())
1373                         return NULL;
1374                 if (!list || tp->head == tp->tail)
1375                         return NULL;
1376
1377                 array = (MonoArray *) mono_mlist_get_data (list);
1378                 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1379                 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1380                 tp->head++;
1381                 if ((tp->head % QUEUE_LENGTH) == 0) {
1382                         list = tp->first;
1383                         tp->first = mono_mlist_next (list);
1384                         if (tp->first == NULL)
1385                                 tp->last = NULL;
1386                         if (mono_mlist_length (tp->unused) < 20) {
1387                                 /* reuse this chunk */
1388                                 tp->unused = mono_mlist_set_next (list, tp->unused);
1389                         }
1390                         tp->head -= QUEUE_LENGTH;
1391                         tp->tail -= QUEUE_LENGTH;
1392                 }
1393                 list = tp->first;
1394         } while (ar == NULL);
1395         return ar;
1396 }
1397
1398 static gboolean
1399 threadpool_start_thread (ThreadPool *tp)
1400 {
1401         gint n;
1402
1403         while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1404                 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1405                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1406                         mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1407                         return TRUE;
1408                 }
1409         }
1410
1411         return FALSE;
1412 }
1413
1414 static void
1415 pulse_on_new_job (ThreadPool *tp)
1416 {
1417         if (tp->waiting)
1418                 MONO_SEM_POST (&tp->new_job);
1419 }
1420
1421 void
1422 icall_append_job (MonoObject *ar)
1423 {
1424         threadpool_append_job (&async_tp, ar);
1425 }
1426
1427 static void
1428 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1429 {
1430         threadpool_append_jobs (tp, &ar, 1);
1431 }
1432
1433 static MonoMList *
1434 create_or_reuse_list (ThreadPool *tp)
1435 {
1436         MonoMList *list;
1437         MonoArray *array;
1438
1439         list = NULL;
1440         if (tp->unused) {
1441                 list = tp->unused;
1442                 tp->unused = mono_mlist_next (list);
1443                 mono_mlist_set_next (list, NULL);
1444                 //TP_DEBUG (tp->nodes_reused++);
1445         } else {
1446                 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1447                 list = mono_mlist_alloc ((MonoObject *) array);
1448                 //TP_DEBUG (tp->nodes_created++);
1449         }
1450         return list;
1451 }
1452
1453 static void
1454 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1455 {
1456         static int job_counter;
1457         MonoArray *array;
1458         MonoMList *list;
1459         MonoObject *ar;
1460         gint i;
1461         gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1462
1463         if (mono_runtime_is_shutting_down ())
1464                 return;
1465
1466         if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1467                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1468
1469         for (i = 0; i < njobs; i++) {
1470                 ar = jobs [i];
1471                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1472                         continue; /* Might happen when cleaning domain jobs */
1473                 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1474                         MonoAsyncResult *o = (MonoAsyncResult *) ar;
1475                         o->add_time = mono_100ns_ticks ();
1476                 }
1477                 threadpool_jobs_inc (ar); 
1478                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1479                 if (!tp->is_io && mono_wsq_local_push (ar))
1480                         continue;
1481
1482                 if (!lock_taken) {
1483                         MONO_SEM_WAIT (&tp->lock);
1484                         lock_taken = TRUE;
1485                 }
1486                 if ((tp->tail % QUEUE_LENGTH) == 0) {
1487                         list = create_or_reuse_list (tp);
1488                         if (tp->last != NULL)
1489                                 mono_mlist_set_next (tp->last, list);
1490                         tp->last = list;
1491                         if (tp->first == NULL)
1492                                 tp->first = tp->last;
1493                 }
1494
1495                 array = (MonoArray *) mono_mlist_get_data (tp->last);
1496                 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1497                 tp->tail++;
1498         }
1499         if (lock_taken)
1500                 MONO_SEM_POST (&tp->lock);
1501
1502         for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1503                 pulse_on_new_job (tp);
1504 }
1505
1506 static void
1507 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1508 {
1509         MonoMList *current;
1510         MonoArray *array;
1511         MonoObject *obj;
1512         int domain_count;
1513         int i;
1514
1515         domain_count = 0;
1516         MONO_SEM_WAIT (&tp->lock);
1517         current = tp->first;
1518         while (current) {
1519                 array = (MonoArray *) mono_mlist_get_data (current);
1520                 for (i = 0; i < QUEUE_LENGTH; i++) {
1521                         obj = mono_array_get (array, MonoObject*, i);
1522                         if (obj != NULL && obj->vtable->domain == domain) {
1523                                 domain_count++;
1524                                 mono_array_setref (array, i, NULL);
1525                                 threadpool_jobs_dec (obj);
1526                         }
1527                 }
1528                 current = mono_mlist_next (current);
1529         }
1530
1531         if (!domain_count) {
1532                 MONO_SEM_POST (&tp->lock);
1533                 return;
1534         }
1535
1536         current = tp->first;
1537         tp->first = NULL;
1538         tp->last = NULL;
1539         tp->head = 0;
1540         tp->tail = 0;
1541         MONO_SEM_POST (&tp->lock);
1542         /* Re-add everything but the nullified elements */
1543         while (current) {
1544                 array = (MonoArray *) mono_mlist_get_data (current);
1545                 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1546                 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1547                 current = mono_mlist_next (current);
1548         }
1549 }
1550
1551 /*
1552  * Clean up the threadpool of all domain jobs.
1553  * Can only be called as part of the domain unloading process as
1554  * it will wait for all jobs to be visible to the interruption code. 
1555  */
1556 gboolean
1557 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1558 {
1559         HANDLE sem_handle;
1560         int result = TRUE;
1561         guint32 start_time = 0;
1562
1563         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1564
1565         threadpool_clear_queue (&async_tp, domain);
1566         threadpool_clear_queue (&async_io_tp, domain);
1567
1568         /*
1569          * There might be some threads out that could be about to execute stuff from the given domain.
1570          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1571          */
1572         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1573
1574         domain->cleanup_semaphore = sem_handle;
1575         /*
1576          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1577          * and reading threadpool_jobs.
1578          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1579          */
1580         mono_memory_write_barrier ();
1581
1582         if (domain->threadpool_jobs && timeout != -1)
1583                 start_time = mono_msec_ticks ();
1584         while (domain->threadpool_jobs) {
1585                 WaitForSingleObject (sem_handle, timeout);
1586                 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1587                         result = FALSE;
1588                         break;
1589                 }
1590         }
1591
1592         domain->cleanup_semaphore = NULL;
1593         CloseHandle (sem_handle);
1594         return result;
1595 }
1596
1597 static void
1598 threadpool_free_queue (ThreadPool *tp)
1599 {
1600         tp->head = tp->tail = 0;
1601         tp->first = NULL;
1602         tp->unused = NULL;
1603 }
1604
1605 gboolean
1606 mono_thread_pool_is_queue_array (MonoArray *o)
1607 {
1608         gpointer obj = o;
1609
1610         // FIXME: need some fix in sgen code.
1611         // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1612         return obj == async_tp.first || obj == async_io_tp.first;
1613 }
1614
1615 static void
1616 add_wsq (MonoWSQ *wsq)
1617 {
1618         int i;
1619
1620         if (wsq == NULL)
1621                 return;
1622
1623         EnterCriticalSection (&wsqs_lock);
1624         if (wsqs == NULL) {
1625                 LeaveCriticalSection (&wsqs_lock);
1626                 return;
1627         }
1628         for (i = 0; i < wsqs->len; i++) {
1629                 if (g_ptr_array_index (wsqs, i) == NULL) {
1630                         wsqs->pdata [i] = wsq;
1631                         LeaveCriticalSection (&wsqs_lock);
1632                         return;
1633                 }
1634         }
1635         g_ptr_array_add (wsqs, wsq);
1636         LeaveCriticalSection (&wsqs_lock);
1637 }
1638
1639 static void
1640 remove_wsq (MonoWSQ *wsq)
1641 {
1642         if (wsq == NULL)
1643                 return;
1644
1645         EnterCriticalSection (&wsqs_lock);
1646         if (wsqs == NULL) {
1647                 LeaveCriticalSection (&wsqs_lock);
1648                 return;
1649         }
1650         g_ptr_array_remove_fast (wsqs, wsq);
1651         LeaveCriticalSection (&wsqs_lock);
1652 }
1653
1654 static void
1655 try_steal (gpointer *data, gboolean retry)
1656 {
1657         int i;
1658         int ms;
1659
1660         if (wsqs == NULL || data == NULL || *data != NULL)
1661                 return;
1662
1663         ms = 0;
1664         do {
1665                 if (mono_runtime_is_shutting_down ())
1666                         return;
1667                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1668                         if (mono_runtime_is_shutting_down ()) {
1669                                 return;
1670                         }
1671                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1672                         if (*data != NULL) {
1673                                 return;
1674                         }
1675                 }
1676                 ms += 10;
1677         } while (retry && ms < 11);
1678 }
1679
1680 static gboolean
1681 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1682 {
1683         if (mono_runtime_is_shutting_down ())
1684                 return FALSE;
1685         TP_DEBUG ("Dequeue");
1686         MONO_SEM_WAIT (&tp->lock);
1687         *data = dequeue_job_nolock (tp);
1688         MONO_SEM_POST (&tp->lock);
1689         if (!tp->is_io && !*data)
1690                 try_steal (data, FALSE);
1691         return (*data != NULL);
1692 }
1693
1694 static void
1695 process_idle_times (ThreadPool *tp, gint64 t)
1696 {
1697         gint64 ticks;
1698         gint64 avg;
1699         gboolean compute_avg;
1700         gint new_threads;
1701         gint64 per1;
1702
1703         if (tp->ignore_times || t <= 0)
1704                 return;
1705
1706         compute_avg = FALSE;
1707         ticks = mono_100ns_ticks ();
1708         t = ticks - t;
1709         SPIN_LOCK (tp->sp_lock);
1710         if (tp->ignore_times) {
1711                 SPIN_UNLOCK (tp->sp_lock);
1712                 return;
1713         }
1714         tp->time_sum += t;
1715         tp->n_sum++;
1716         if (tp->last_check == 0)
1717                 tp->last_check = ticks;
1718         else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1719                 tp->ignore_times = 1;
1720                 compute_avg = TRUE;
1721         }
1722         SPIN_UNLOCK (tp->sp_lock);
1723
1724         if (!compute_avg)
1725                 return;
1726
1727         //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1728         tp->last_check = ticks;
1729         new_threads = 0;
1730         avg = tp->time_sum / tp->n_sum;
1731         if (tp->averages [1] == 0) {
1732                 tp->averages [1] = avg;
1733         } else {
1734                 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1735                 if (per1 > 5) {
1736                         if (avg > tp->averages [1]) {
1737                                 if (tp->averages [1] < tp->averages [0]) {
1738                                         new_threads = -1;
1739                                 } else {
1740                                         new_threads = 1;
1741                                 }
1742                         } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1743                                 new_threads = 1;
1744                         }
1745                 } else {
1746                         int min, n;
1747                         min = tp->min_threads;
1748                         n = tp->nthreads;
1749                         if ((n - min) < min && tp->busy_threads == n)
1750                                 new_threads = 1;
1751                 }
1752                 /*
1753                 if (new_threads != 0) {
1754                         printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1755                 }
1756                 */
1757         }
1758
1759         tp->time_sum = 0;
1760         tp->n_sum = 0;
1761
1762         tp->averages [0] = tp->averages [1];
1763         tp->averages [1] = avg;
1764         tp->ignore_times = 0;
1765
1766         if (new_threads == -1) {
1767                 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1768                         pulse_on_new_job (tp);
1769         }
1770 }
1771
1772 static gboolean
1773 should_i_die (ThreadPool *tp)
1774 {
1775         gboolean result = FALSE;
1776         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1777                 result = (tp->nthreads > tp->min_threads);
1778         return result;
1779 }
1780
1781 static void
1782 async_invoke_thread (gpointer data)
1783 {
1784         MonoDomain *domain;
1785         MonoInternalThread *thread;
1786         MonoWSQ *wsq;
1787         ThreadPool *tp;
1788         gboolean must_die;
1789   
1790         tp = data;
1791         wsq = NULL;
1792         if (!tp->is_io) {
1793                 wsq = mono_wsq_create ();
1794                 add_wsq (wsq);
1795         }
1796
1797         thread = mono_thread_internal_current ();
1798         if (tp_start_func)
1799                 tp_start_func (tp_hooks_user_data);
1800         data = NULL;
1801         for (;;) {
1802                 MonoAsyncResult *ar;
1803                 gboolean is_io_task;
1804                 int n_naps = 0;
1805
1806                 is_io_task = FALSE;
1807                 ar = (MonoAsyncResult *) data;
1808                 if (ar) {
1809                         InterlockedIncrement (&tp->busy_threads);
1810 #ifndef DISABLE_SOCKETS
1811                         is_io_task = (strcmp (((MonoObject *) data)->vtable->klass->name, "AsyncResult"));
1812                         if (is_io_task) {
1813                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1814                                 ar = state->ares;
1815                                 switch (state->operation) {
1816                                 case AIO_OP_RECEIVE:
1817                                         state->total = ICALL_RECV (state);
1818                                         break;
1819                                 case AIO_OP_SEND:
1820                                         state->total = ICALL_SEND (state);
1821                                         break;
1822                                 }
1823                         }
1824 #endif
1825                         /* worker threads invokes methods in different domains,
1826                          * so we need to set the right domain here */
1827                         domain = ((MonoObject *)ar)->vtable->domain;
1828                         g_assert (domain);
1829
1830                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1831                                 threadpool_jobs_dec ((MonoObject *)ar);
1832                                 data = NULL;
1833                                 ar = NULL;
1834                                 InterlockedDecrement (&tp->busy_threads);
1835                         } else {
1836                                 mono_thread_push_appdomain_ref (domain);
1837                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1838                                         data = NULL;
1839                                         ar = NULL;
1840                                         mono_thread_pop_appdomain_ref ();
1841                                         InterlockedDecrement (&tp->busy_threads);
1842                                         continue;
1843                                 }
1844
1845                                 if (mono_domain_set (domain, FALSE)) {
1846                                         MonoObject *exc;
1847
1848                                         if (tp_item_begin_func)
1849                                                 tp_item_begin_func (tp_item_user_data);
1850
1851                                         if (!is_io_task && ar->add_time > 0)
1852                                                 process_idle_times (tp, ar->add_time);
1853                                         exc = mono_async_invoke (tp, ar);
1854                                         if (tp_item_end_func)
1855                                                 tp_item_end_func (tp_item_user_data);
1856                                         if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1857                                                 mono_unhandled_exception (exc);
1858                                                 exit (255);
1859                                         }
1860                                         mono_domain_set (mono_get_root_domain (), TRUE);
1861                                 }
1862                                 mono_thread_pop_appdomain_ref ();
1863                                 InterlockedDecrement (&tp->busy_threads);
1864                                 /* If the callee changes the background status, set it back to TRUE */
1865                                 if (!mono_thread_test_state (thread , ThreadState_Background))
1866                                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1867                         }
1868                 }
1869
1870                 ar = NULL;
1871                 data = NULL;
1872                 must_die = should_i_die (tp);
1873                 TP_DEBUG ("Trying to get a job");
1874                 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1875                         dequeue_or_steal (tp, &data);
1876                 TP_DEBUG ("Done trying to get a job %p", data);
1877
1878                 n_naps = 0;
1879                 while (!must_die && !data && n_naps < 4) {
1880                         gboolean res;
1881
1882                         TP_DEBUG ("Waiting");
1883                         InterlockedIncrement (&tp->waiting);
1884 #if defined(__OpenBSD__)
1885                         while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1886 #else
1887                         while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1888 #endif
1889                                 if (mono_runtime_is_shutting_down ())
1890                                         break;
1891                                 if (THREAD_WANTS_A_BREAK (thread))
1892                                         mono_thread_interruption_checkpoint ();
1893                         }
1894                         TP_DEBUG ("Done waiting");
1895                         InterlockedDecrement (&tp->waiting);
1896                         if (mono_runtime_is_shutting_down ())
1897                                 break;
1898                         must_die = should_i_die (tp);
1899                         dequeue_or_steal (tp, &data);
1900                         n_naps++;
1901                 }
1902
1903                 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
1904                         mono_wsq_local_pop (&data);
1905                         if (data && must_die) {
1906                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1907                                 pulse_on_new_job (tp);
1908                         }
1909                 }
1910
1911                 if (!data) {
1912                         gint nt;
1913                         gboolean down;
1914                         while (1) {
1915                                 nt = tp->nthreads;
1916                                 down = mono_runtime_is_shutting_down ();
1917                                 if (!down && nt <= tp->min_threads)
1918                                         break;
1919                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1920                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1921                                         TP_DEBUG ("DIE");
1922                                         if (!tp->is_io) {
1923                                                 remove_wsq (wsq);
1924                                                 while (mono_wsq_local_pop (&data)) {
1925                                                         threadpool_jobs_dec (data);
1926                                                         data = NULL;
1927                                                 }
1928                                                 mono_wsq_destroy (wsq);
1929                                         }
1930                                         if (tp_finish_func)
1931                                                 tp_finish_func (tp_hooks_user_data);
1932                                         return;
1933                                 }
1934                         }
1935                 }
1936         }
1937
1938         g_assert_not_reached ();
1939 }
1940
1941 void
1942 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1943 {
1944         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1945         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1946 }
1947
1948 void
1949 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1950 {
1951         *workerThreads = async_tp.max_threads;
1952         *completionPortThreads = async_io_tp.max_threads;
1953 }
1954
1955 void
1956 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1957 {
1958         *workerThreads = async_tp.min_threads;
1959         *completionPortThreads = async_io_tp.min_threads;
1960 }
1961
1962 MonoBoolean
1963 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1964 {
1965         gint max_threads;
1966         gint max_io_threads;
1967
1968         max_threads = async_tp.max_threads;
1969         if (workerThreads <= 0 || workerThreads > max_threads)
1970                 return FALSE;
1971
1972         max_io_threads = async_io_tp.max_threads;
1973         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1974                 return FALSE;
1975
1976         InterlockedExchange (&async_tp.min_threads, workerThreads);
1977         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1978         if (workerThreads > async_tp.nthreads)
1979                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
1980         if (completionPortThreads > async_io_tp.nthreads)
1981                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
1982         return TRUE;
1983 }
1984
1985 MonoBoolean
1986 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1987 {
1988         gint min_threads;
1989         gint min_io_threads;
1990         gint cpu_count;
1991
1992         cpu_count = mono_cpu_count ();
1993         min_threads = async_tp.min_threads;
1994         if (workerThreads < min_threads || workerThreads < cpu_count)
1995                 return FALSE;
1996
1997         /* We don't really have the concept of completion ports. Do we care here? */
1998         min_io_threads = async_io_tp.min_threads;
1999         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2000                 return FALSE;
2001
2002         InterlockedExchange (&async_tp.max_threads, workerThreads);
2003         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2004         return TRUE;
2005 }
2006
2007 /**
2008  * mono_install_threadpool_thread_hooks
2009  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2010  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2011  * @user_data: argument passed to @start_func and @finish_func.
2012  *
2013  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2014  * The calls will be made from the thread itself.
2015  */
2016 void
2017 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2018 {
2019         tp_start_func = start_func;
2020         tp_finish_func = finish_func;
2021         tp_hooks_user_data = user_data;
2022 }
2023
2024 /**
2025  * mono_install_threadpool_item_hooks
2026  * @begin_func: the function to be called before a threadpool work item processing starts.
2027  * @end_func: the function to be called after a threadpool work item is finished.
2028  * @user_data: argument passed to @begin_func and @end_func.
2029  *
2030  * The calls will be made from the thread itself and from the same AppDomain
2031  * where the work item was executed.
2032  *
2033  */
2034 void
2035 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2036 {
2037         tp_item_begin_func = begin_func;
2038         tp_item_end_func = end_func;
2039         tp_item_user_data = user_data;
2040 }
2041