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