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