Bypass BeginInvoke for asynch. operations
[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 void
1258 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1259 {
1260         MonoDomain *domain = mono_domain_get ();
1261         MonoAsyncResult *ares;
1262
1263         /* Don't call mono_async_result_new() to avoid capturing the context */
1264         ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1265         MONO_OBJECT_SETREF (ares, async_delegate, target);
1266         MONO_OBJECT_SETREF (ares, async_state, state);
1267         socket_io_add (ares, state);
1268 }
1269
1270 MonoAsyncResult *
1271 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1272                       MonoObject *state)
1273 {
1274         MonoDomain *domain = mono_domain_get ();
1275         MonoAsyncResult *ares;
1276         ASyncCall *ac;
1277
1278         ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1279         MONO_OBJECT_SETREF (ac, msg, msg);
1280         MONO_OBJECT_SETREF (ac, state, state);
1281
1282         if (async_callback) {
1283                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1284                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1285         }
1286
1287         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1288         MONO_OBJECT_SETREF (ares, async_delegate, target);
1289
1290 #ifndef DISABLE_SOCKETS
1291         if (socket_io_filter (target, state)) {
1292                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1293                 return ares;
1294         }
1295 #endif
1296         threadpool_append_job (&async_tp, (MonoObject *) ares);
1297         return ares;
1298 }
1299
1300 MonoObject *
1301 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1302 {
1303         ASyncCall *ac;
1304         HANDLE wait_event;
1305
1306         *exc = NULL;
1307         *out_args = NULL;
1308
1309         /* check if already finished */
1310         mono_monitor_enter ((MonoObject *) ares);
1311         
1312         if (ares->endinvoke_called) {
1313                 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1314                 mono_monitor_exit ((MonoObject *) ares);
1315                 return NULL;
1316         }
1317
1318         ares->endinvoke_called = 1;
1319         /* wait until we are really finished */
1320         if (!ares->completed) {
1321                 if (ares->handle == NULL) {
1322                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1323                         g_assert(wait_event != 0);
1324                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1325                 } else {
1326                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1327                 }
1328                 mono_monitor_exit ((MonoObject *) ares);
1329                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1330         } else {
1331                 mono_monitor_exit ((MonoObject *) ares);
1332         }
1333
1334         ac = (ASyncCall *) ares->object_data;
1335         g_assert (ac != NULL);
1336         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1337         *out_args = ac->out_args;
1338
1339         return ac->res;
1340 }
1341
1342 static void
1343 threadpool_kill_idle_threads (ThreadPool *tp)
1344 {
1345         gint n;
1346
1347         n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1348         while (n) {
1349                 n--;
1350                 MONO_SEM_POST (&tp->new_job);
1351         }
1352 }
1353
1354 void
1355 mono_thread_pool_cleanup (void)
1356 {
1357         if (!(async_tp.pool_status == 0 || async_tp.pool_status == 2)) {
1358                 if (!(async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)) {
1359                         InterlockedExchange (&async_io_tp.pool_status, 2);
1360                         MONO_SEM_WAIT (&async_tp.lock);
1361                         threadpool_free_queue (&async_tp);
1362                         threadpool_kill_idle_threads (&async_tp);
1363                         MONO_SEM_POST (&async_tp.lock);
1364
1365                         socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1366                         MONO_SEM_WAIT (&async_io_tp.lock);
1367                         threadpool_free_queue (&async_io_tp);
1368                         threadpool_kill_idle_threads (&async_io_tp);
1369                         MONO_SEM_POST (&async_io_tp.lock);
1370                         MONO_SEM_DESTROY (&async_io_tp.new_job);
1371                 }
1372         }
1373
1374         EnterCriticalSection (&wsqs_lock);
1375         mono_wsq_cleanup ();
1376         if (wsqs)
1377                 g_ptr_array_free (wsqs, TRUE);
1378         wsqs = NULL;
1379         LeaveCriticalSection (&wsqs_lock);
1380         MONO_SEM_DESTROY (&async_tp.new_job);
1381 }
1382
1383 /* Caller must enter &tp->lock */
1384 static MonoObject*
1385 dequeue_job_nolock (ThreadPool *tp)
1386 {
1387         MonoObject *ar;
1388         MonoArray *array;
1389         MonoMList *list;
1390
1391         list = tp->first;
1392         do {
1393                 if (mono_runtime_is_shutting_down ())
1394                         return NULL;
1395                 if (!list || tp->head == tp->tail)
1396                         return NULL;
1397
1398                 array = (MonoArray *) mono_mlist_get_data (list);
1399                 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1400                 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1401                 tp->head++;
1402                 if ((tp->head % QUEUE_LENGTH) == 0) {
1403                         list = tp->first;
1404                         tp->first = mono_mlist_next (list);
1405                         if (tp->first == NULL)
1406                                 tp->last = NULL;
1407                         if (mono_mlist_length (tp->unused) < 20) {
1408                                 /* reuse this chunk */
1409                                 tp->unused = mono_mlist_set_next (list, tp->unused);
1410                         }
1411                         tp->head -= QUEUE_LENGTH;
1412                         tp->tail -= QUEUE_LENGTH;
1413                 }
1414                 list = tp->first;
1415         } while (ar == NULL);
1416         return ar;
1417 }
1418
1419 static gboolean
1420 threadpool_start_thread (ThreadPool *tp)
1421 {
1422         gint n;
1423
1424         while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1425                 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1426                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1427                         mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1428                         return TRUE;
1429                 }
1430         }
1431
1432         return FALSE;
1433 }
1434
1435 static void
1436 pulse_on_new_job (ThreadPool *tp)
1437 {
1438         if (tp->waiting)
1439                 MONO_SEM_POST (&tp->new_job);
1440 }
1441
1442 void
1443 icall_append_job (MonoObject *ar)
1444 {
1445         threadpool_append_job (&async_tp, ar);
1446 }
1447
1448 static void
1449 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1450 {
1451         threadpool_append_jobs (tp, &ar, 1);
1452 }
1453
1454 static MonoMList *
1455 create_or_reuse_list (ThreadPool *tp)
1456 {
1457         MonoMList *list;
1458         MonoArray *array;
1459
1460         list = NULL;
1461         if (tp->unused) {
1462                 list = tp->unused;
1463                 tp->unused = mono_mlist_next (list);
1464                 mono_mlist_set_next (list, NULL);
1465                 //TP_DEBUG (tp->nodes_reused++);
1466         } else {
1467                 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1468                 list = mono_mlist_alloc ((MonoObject *) array);
1469                 //TP_DEBUG (tp->nodes_created++);
1470         }
1471         return list;
1472 }
1473
1474 static void
1475 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1476 {
1477         static int job_counter;
1478         MonoArray *array;
1479         MonoMList *list;
1480         MonoObject *ar;
1481         gint i;
1482         gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1483
1484         if (mono_runtime_is_shutting_down ())
1485                 return;
1486
1487         if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1488                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1489
1490         for (i = 0; i < njobs; i++) {
1491                 ar = jobs [i];
1492                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1493                         continue; /* Might happen when cleaning domain jobs */
1494                 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1495                         MonoAsyncResult *o = (MonoAsyncResult *) ar;
1496                         o->add_time = mono_100ns_ticks ();
1497                 }
1498                 threadpool_jobs_inc (ar); 
1499                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1500                 if (!tp->is_io && mono_wsq_local_push (ar))
1501                         continue;
1502
1503                 if (!lock_taken) {
1504                         MONO_SEM_WAIT (&tp->lock);
1505                         lock_taken = TRUE;
1506                 }
1507                 if ((tp->tail % QUEUE_LENGTH) == 0) {
1508                         list = create_or_reuse_list (tp);
1509                         if (tp->last != NULL)
1510                                 mono_mlist_set_next (tp->last, list);
1511                         tp->last = list;
1512                         if (tp->first == NULL)
1513                                 tp->first = tp->last;
1514                 }
1515
1516                 array = (MonoArray *) mono_mlist_get_data (tp->last);
1517                 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1518                 tp->tail++;
1519         }
1520         if (lock_taken)
1521                 MONO_SEM_POST (&tp->lock);
1522
1523         for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1524                 pulse_on_new_job (tp);
1525 }
1526
1527 static void
1528 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1529 {
1530         MonoMList *current;
1531         MonoArray *array;
1532         MonoObject *obj;
1533         int domain_count;
1534         int i;
1535
1536         domain_count = 0;
1537         MONO_SEM_WAIT (&tp->lock);
1538         current = tp->first;
1539         while (current) {
1540                 array = (MonoArray *) mono_mlist_get_data (current);
1541                 for (i = 0; i < QUEUE_LENGTH; i++) {
1542                         obj = mono_array_get (array, MonoObject*, i);
1543                         if (obj != NULL && obj->vtable->domain == domain) {
1544                                 domain_count++;
1545                                 mono_array_setref (array, i, NULL);
1546                                 threadpool_jobs_dec (obj);
1547                         }
1548                 }
1549                 current = mono_mlist_next (current);
1550         }
1551
1552         if (!domain_count) {
1553                 MONO_SEM_POST (&tp->lock);
1554                 return;
1555         }
1556
1557         current = tp->first;
1558         tp->first = NULL;
1559         tp->last = NULL;
1560         tp->head = 0;
1561         tp->tail = 0;
1562         MONO_SEM_POST (&tp->lock);
1563         /* Re-add everything but the nullified elements */
1564         while (current) {
1565                 array = (MonoArray *) mono_mlist_get_data (current);
1566                 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1567                 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1568                 current = mono_mlist_next (current);
1569         }
1570 }
1571
1572 /*
1573  * Clean up the threadpool of all domain jobs.
1574  * Can only be called as part of the domain unloading process as
1575  * it will wait for all jobs to be visible to the interruption code. 
1576  */
1577 gboolean
1578 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1579 {
1580         HANDLE sem_handle;
1581         int result = TRUE;
1582         guint32 start_time = 0;
1583
1584         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1585
1586         threadpool_clear_queue (&async_tp, domain);
1587         threadpool_clear_queue (&async_io_tp, domain);
1588
1589         /*
1590          * There might be some threads out that could be about to execute stuff from the given domain.
1591          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1592          */
1593         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1594
1595         domain->cleanup_semaphore = sem_handle;
1596         /*
1597          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1598          * and reading threadpool_jobs.
1599          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1600          */
1601         mono_memory_write_barrier ();
1602
1603         if (domain->threadpool_jobs && timeout != -1)
1604                 start_time = mono_msec_ticks ();
1605         while (domain->threadpool_jobs) {
1606                 WaitForSingleObject (sem_handle, timeout);
1607                 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1608                         result = FALSE;
1609                         break;
1610                 }
1611         }
1612
1613         domain->cleanup_semaphore = NULL;
1614         CloseHandle (sem_handle);
1615         return result;
1616 }
1617
1618 static void
1619 threadpool_free_queue (ThreadPool *tp)
1620 {
1621         tp->head = tp->tail = 0;
1622         tp->first = NULL;
1623         tp->unused = NULL;
1624 }
1625
1626 gboolean
1627 mono_thread_pool_is_queue_array (MonoArray *o)
1628 {
1629         gpointer obj = o;
1630
1631         // FIXME: need some fix in sgen code.
1632         // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1633         return obj == async_tp.first || obj == async_io_tp.first;
1634 }
1635
1636 static MonoWSQ *
1637 add_wsq (void)
1638 {
1639         int i;
1640         MonoWSQ *wsq;
1641
1642         EnterCriticalSection (&wsqs_lock);
1643         wsq = mono_wsq_create ();
1644         if (wsqs == NULL) {
1645                 LeaveCriticalSection (&wsqs_lock);
1646                 return NULL;
1647         }
1648         for (i = 0; i < wsqs->len; i++) {
1649                 if (g_ptr_array_index (wsqs, i) == NULL) {
1650                         wsqs->pdata [i] = wsq;
1651                         LeaveCriticalSection (&wsqs_lock);
1652                         return wsq;
1653                 }
1654         }
1655         g_ptr_array_add (wsqs, wsq);
1656         LeaveCriticalSection (&wsqs_lock);
1657         return wsq;
1658 }
1659
1660 static void
1661 remove_wsq (MonoWSQ *wsq)
1662 {
1663         gpointer data;
1664
1665         if (wsq == NULL)
1666                 return;
1667
1668         EnterCriticalSection (&wsqs_lock);
1669         if (wsqs == NULL) {
1670                 LeaveCriticalSection (&wsqs_lock);
1671                 return;
1672         }
1673         g_ptr_array_remove_fast (wsqs, wsq);
1674         data = NULL;
1675         while (mono_wsq_local_pop (&data)) {
1676                 threadpool_jobs_dec (data);
1677                 data = NULL;
1678         }
1679         mono_wsq_destroy (wsq);
1680         LeaveCriticalSection (&wsqs_lock);
1681 }
1682
1683 static void
1684 try_steal (gpointer *data, gboolean retry)
1685 {
1686         int i;
1687         int ms;
1688
1689         if (wsqs == NULL || data == NULL || *data != NULL)
1690                 return;
1691
1692         ms = 0;
1693         do {
1694                 if (mono_runtime_is_shutting_down ())
1695                         return;
1696                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1697                         if (mono_runtime_is_shutting_down ()) {
1698                                 return;
1699                         }
1700                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1701                         if (*data != NULL) {
1702                                 return;
1703                         }
1704                 }
1705                 ms += 10;
1706         } while (retry && ms < 11);
1707 }
1708
1709 static gboolean
1710 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1711 {
1712         if (mono_runtime_is_shutting_down ())
1713                 return FALSE;
1714         TP_DEBUG ("Dequeue");
1715         MONO_SEM_WAIT (&tp->lock);
1716         *data = dequeue_job_nolock (tp);
1717         MONO_SEM_POST (&tp->lock);
1718         if (!tp->is_io && !*data)
1719                 try_steal (data, FALSE);
1720         return (*data != NULL);
1721 }
1722
1723 static void
1724 process_idle_times (ThreadPool *tp, gint64 t)
1725 {
1726         gint64 ticks;
1727         gint64 avg;
1728         gboolean compute_avg;
1729         gint new_threads;
1730         gint64 per1;
1731
1732         if (tp->ignore_times || t <= 0)
1733                 return;
1734
1735         compute_avg = FALSE;
1736         ticks = mono_100ns_ticks ();
1737         t = ticks - t;
1738         SPIN_LOCK (tp->sp_lock);
1739         if (tp->ignore_times) {
1740                 SPIN_UNLOCK (tp->sp_lock);
1741                 return;
1742         }
1743         tp->time_sum += t;
1744         tp->n_sum++;
1745         if (tp->last_check == 0)
1746                 tp->last_check = ticks;
1747         else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1748                 tp->ignore_times = 1;
1749                 compute_avg = TRUE;
1750         }
1751         SPIN_UNLOCK (tp->sp_lock);
1752
1753         if (!compute_avg)
1754                 return;
1755
1756         //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1757         tp->last_check = ticks;
1758         new_threads = 0;
1759         avg = tp->time_sum / tp->n_sum;
1760         if (tp->averages [1] == 0) {
1761                 tp->averages [1] = avg;
1762         } else {
1763                 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1764                 if (per1 > 5) {
1765                         if (avg > tp->averages [1]) {
1766                                 if (tp->averages [1] < tp->averages [0]) {
1767                                         new_threads = -1;
1768                                 } else {
1769                                         new_threads = 1;
1770                                 }
1771                         } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1772                                 new_threads = 1;
1773                         }
1774                 } else {
1775                         int min, n;
1776                         min = tp->min_threads;
1777                         n = tp->nthreads;
1778                         if ((n - min) < min && tp->busy_threads == n)
1779                                 new_threads = 1;
1780                 }
1781                 /*
1782                 if (new_threads != 0) {
1783                         printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1784                 }
1785                 */
1786         }
1787
1788         tp->time_sum = 0;
1789         tp->n_sum = 0;
1790
1791         tp->averages [0] = tp->averages [1];
1792         tp->averages [1] = avg;
1793         tp->ignore_times = 0;
1794
1795         if (new_threads == -1) {
1796                 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1797                         pulse_on_new_job (tp);
1798         }
1799 }
1800
1801 static gboolean
1802 should_i_die (ThreadPool *tp)
1803 {
1804         gboolean result = FALSE;
1805         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1806                 result = (tp->nthreads > tp->min_threads);
1807         return result;
1808 }
1809
1810 static void
1811 async_invoke_thread (gpointer data)
1812 {
1813         MonoDomain *domain;
1814         MonoInternalThread *thread;
1815         MonoWSQ *wsq;
1816         ThreadPool *tp;
1817         gboolean must_die;
1818   
1819         tp = data;
1820         wsq = NULL;
1821         if (!tp->is_io)
1822                 wsq = add_wsq ();
1823
1824         thread = mono_thread_internal_current ();
1825         if (tp_start_func)
1826                 tp_start_func (tp_hooks_user_data);
1827         data = NULL;
1828         for (;;) {
1829                 MonoAsyncResult *ar;
1830                 gboolean is_io_task;
1831                 int n_naps = 0;
1832
1833                 is_io_task = FALSE;
1834                 ar = (MonoAsyncResult *) data;
1835                 if (ar) {
1836                         InterlockedIncrement (&tp->busy_threads);
1837 #ifndef DISABLE_SOCKETS
1838                         is_io_task = (strcmp (((MonoObject *) data)->vtable->klass->name, "AsyncResult"));
1839                         if (is_io_task) {
1840                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1841                                 ar = state->ares;
1842                                 switch (state->operation) {
1843                                 case AIO_OP_RECEIVE:
1844                                         state->total = ICALL_RECV (state);
1845                                         break;
1846                                 case AIO_OP_SEND:
1847                                         state->total = ICALL_SEND (state);
1848                                         break;
1849                                 }
1850                         }
1851 #endif
1852                         /* worker threads invokes methods in different domains,
1853                          * so we need to set the right domain here */
1854                         domain = ((MonoObject *)ar)->vtable->domain;
1855                         g_assert (domain);
1856
1857                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1858                                 threadpool_jobs_dec ((MonoObject *)ar);
1859                                 data = NULL;
1860                                 ar = NULL;
1861                                 InterlockedDecrement (&tp->busy_threads);
1862                         } else {
1863                                 mono_thread_push_appdomain_ref (domain);
1864                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1865                                         data = NULL;
1866                                         ar = NULL;
1867                                         mono_thread_pop_appdomain_ref ();
1868                                         InterlockedDecrement (&tp->busy_threads);
1869                                         continue;
1870                                 }
1871
1872                                 if (mono_domain_set (domain, FALSE)) {
1873                                         MonoObject *exc;
1874
1875                                         if (tp_item_begin_func)
1876                                                 tp_item_begin_func (tp_item_user_data);
1877
1878                                         if (!is_io_task && ar->add_time > 0)
1879                                                 process_idle_times (tp, ar->add_time);
1880                                         exc = mono_async_invoke (tp, ar);
1881                                         if (tp_item_end_func)
1882                                                 tp_item_end_func (tp_item_user_data);
1883                                         if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1884                                                 gboolean unloaded;
1885                                                 MonoClass *klass;
1886
1887                                                 klass = exc->vtable->klass;
1888                                                 unloaded = (klass->image == mono_defaults.corlib);
1889                                                 if (unloaded) {
1890                                                         unloaded = (!strcmp ("System", klass->name_space) &&
1891                                                                 !strcmp ("AppDomainUnloadedException", klass->name));
1892                                                 }
1893
1894                                                 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1895                                                         mono_unhandled_exception (exc);
1896                                                         exit (255);
1897                                                 }
1898                                         }
1899                                         mono_domain_set (mono_get_root_domain (), TRUE);
1900                                 }
1901                                 mono_thread_pop_appdomain_ref ();
1902                                 InterlockedDecrement (&tp->busy_threads);
1903                                 /* If the callee changes the background status, set it back to TRUE */
1904                                 if (!mono_thread_test_state (thread , ThreadState_Background))
1905                                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1906                         }
1907                 }
1908
1909                 ar = NULL;
1910                 data = NULL;
1911                 must_die = should_i_die (tp);
1912                 TP_DEBUG ("Trying to get a job");
1913                 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1914                         dequeue_or_steal (tp, &data);
1915                 TP_DEBUG ("Done trying to get a job %p", data);
1916
1917                 n_naps = 0;
1918                 while (!must_die && !data && n_naps < 4) {
1919                         gboolean res;
1920
1921                         TP_DEBUG ("Waiting");
1922                         InterlockedIncrement (&tp->waiting);
1923 #if defined(__OpenBSD__)
1924                         while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1925 #else
1926                         while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1927 #endif
1928                                 if (mono_runtime_is_shutting_down ())
1929                                         break;
1930                                 if (THREAD_WANTS_A_BREAK (thread))
1931                                         mono_thread_interruption_checkpoint ();
1932                         }
1933                         TP_DEBUG ("Done waiting");
1934                         InterlockedDecrement (&tp->waiting);
1935                         if (mono_runtime_is_shutting_down ())
1936                                 break;
1937                         must_die = should_i_die (tp);
1938                         dequeue_or_steal (tp, &data);
1939                         n_naps++;
1940                 }
1941
1942                 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
1943                         mono_wsq_local_pop (&data);
1944                         if (data && must_die) {
1945                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1946                                 pulse_on_new_job (tp);
1947                         }
1948                 }
1949
1950                 if (!data) {
1951                         gint nt;
1952                         gboolean down;
1953                         while (1) {
1954                                 nt = tp->nthreads;
1955                                 down = mono_runtime_is_shutting_down ();
1956                                 if (!down && nt <= tp->min_threads)
1957                                         break;
1958                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1959                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1960                                         TP_DEBUG ("DIE");
1961                                         if (!tp->is_io) {
1962                                                 remove_wsq (wsq);
1963                                         }
1964                                         if (tp_finish_func)
1965                                                 tp_finish_func (tp_hooks_user_data);
1966                                         return;
1967                                 }
1968                         }
1969                 }
1970         }
1971
1972         g_assert_not_reached ();
1973 }
1974
1975 void
1976 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1977 {
1978         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1979         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1980 }
1981
1982 void
1983 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1984 {
1985         *workerThreads = async_tp.max_threads;
1986         *completionPortThreads = async_io_tp.max_threads;
1987 }
1988
1989 void
1990 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1991 {
1992         *workerThreads = async_tp.min_threads;
1993         *completionPortThreads = async_io_tp.min_threads;
1994 }
1995
1996 MonoBoolean
1997 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1998 {
1999         gint max_threads;
2000         gint max_io_threads;
2001
2002         max_threads = async_tp.max_threads;
2003         if (workerThreads <= 0 || workerThreads > max_threads)
2004                 return FALSE;
2005
2006         max_io_threads = async_io_tp.max_threads;
2007         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
2008                 return FALSE;
2009
2010         InterlockedExchange (&async_tp.min_threads, workerThreads);
2011         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
2012         if (workerThreads > async_tp.nthreads)
2013                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
2014         if (completionPortThreads > async_io_tp.nthreads)
2015                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
2016         return TRUE;
2017 }
2018
2019 MonoBoolean
2020 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
2021 {
2022         gint min_threads;
2023         gint min_io_threads;
2024         gint cpu_count;
2025
2026         cpu_count = mono_cpu_count ();
2027         min_threads = async_tp.min_threads;
2028         if (workerThreads < min_threads || workerThreads < cpu_count)
2029                 return FALSE;
2030
2031         /* We don't really have the concept of completion ports. Do we care here? */
2032         min_io_threads = async_io_tp.min_threads;
2033         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2034                 return FALSE;
2035
2036         InterlockedExchange (&async_tp.max_threads, workerThreads);
2037         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2038         return TRUE;
2039 }
2040
2041 /**
2042  * mono_install_threadpool_thread_hooks
2043  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2044  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2045  * @user_data: argument passed to @start_func and @finish_func.
2046  *
2047  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2048  * The calls will be made from the thread itself.
2049  */
2050 void
2051 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2052 {
2053         tp_start_func = start_func;
2054         tp_finish_func = finish_func;
2055         tp_hooks_user_data = user_data;
2056 }
2057
2058 /**
2059  * mono_install_threadpool_item_hooks
2060  * @begin_func: the function to be called before a threadpool work item processing starts.
2061  * @end_func: the function to be called after a threadpool work item is finished.
2062  * @user_data: argument passed to @begin_func and @end_func.
2063  *
2064  * The calls will be made from the thread itself and from the same AppDomain
2065  * where the work item was executed.
2066  *
2067  */
2068 void
2069 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2070 {
2071         tp_item_begin_func = begin_func;
2072         tp_item_end_func = end_func;
2073         tp_item_user_data = user_data;
2074 }
2075