Clearing the queue messed up with the per-domain job count
[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 #include <mono/metadata/profiler-private.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/metadata/threads-types.h>
18 #include <mono/metadata/threadpool-internals.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/mono-mlist.h>
21 #include <mono/metadata/mono-perfcounters.h>
22 #include <mono/metadata/socket-io.h>
23 #include <mono/metadata/mono-cq.h>
24 #include <mono/metadata/mono-wsq.h>
25 #include <mono/io-layer/io-layer.h>
26 #include <mono/utils/mono-time.h>
27 #include <mono/utils/mono-proclib.h>
28 #include <mono/utils/mono-semaphore.h>
29 #include <errno.h>
30 #ifdef HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33 #include <sys/types.h>
34 #include <fcntl.h>
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #include <string.h>
39 #ifdef HAVE_SYS_SOCKET_H
40 #include <sys/socket.h>
41 #endif
42 #include <mono/utils/mono-poll.h>
43 #ifdef HAVE_EPOLL
44 #include <sys/epoll.h>
45 #endif
46 #ifdef HAVE_KQUEUE
47 #include <sys/event.h>
48 #endif
49
50
51 #ifndef DISABLE_SOCKETS
52 #include "mono/io-layer/socket-wrappers.h"
53 #endif
54
55 #include "threadpool.h"
56
57 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
58                                                 ThreadState_SuspendRequested)) != 0)
59
60 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
61 #define SPIN_LOCK(i) do { \
62                                 if (SPIN_TRYLOCK (i)) \
63                                         break; \
64                         } while (1)
65
66 #define SPIN_UNLOCK(i) i = 0
67 #define SMALL_STACK (128 * (sizeof (gpointer) / 4) * 1024)
68
69 /* DEBUG: prints tp data every 2s */
70 #undef DEBUG 
71
72 /* mono_thread_pool_init called */
73 static volatile int tp_inited;
74
75 enum {
76         POLL_BACKEND,
77         EPOLL_BACKEND,
78         KQUEUE_BACKEND
79 };
80
81 typedef struct {
82         CRITICAL_SECTION io_lock; /* access to sock_to_state */
83         int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
84         MonoGHashTable *sock_to_state;
85
86         gint event_system;
87         gpointer event_data;
88         void (*modify) (gpointer event_data, int fd, int operation, int events, gboolean is_new);
89         void (*wait) (gpointer sock_data);
90         void (*shutdown) (gpointer event_data);
91 } SocketIOData;
92
93 static SocketIOData socket_io_data;
94
95 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
96 typedef struct {
97         MonoObject         object;
98         MonoMethodMessage *msg;
99         MonoMethod        *cb_method;
100         MonoDelegate      *cb_target;
101         MonoObject        *state;
102         MonoObject        *res;
103         MonoArray         *out_args;
104 } ASyncCall;
105
106 typedef struct {
107         MonoSemType lock;
108         MonoCQ *queue; /* GC root */
109         MonoSemType new_job;
110         volatile gint waiting; /* threads waiting for a work item */
111
112         /**/
113         volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
114         /* min, max, n and busy -> Interlocked */
115         volatile gint min_threads;
116         volatile gint max_threads;
117         volatile gint nthreads;
118         volatile gint busy_threads;
119
120         void (*async_invoke) (gpointer data);
121         void *pc_nitems; /* Performance counter for total number of items in added */
122         void *pc_nthreads; /* Performance counter for total number of active threads */
123         /**/
124         volatile gint destroy_thread;
125         volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
126         volatile gint sp_lock; /* spin lock used to protect ignore_times */
127         volatile gint64 last_check;
128         volatile gint64 time_sum;
129         volatile gint n_sum;
130         gint64 averages [2];
131         gboolean is_io;
132 } ThreadPool;
133
134 static ThreadPool async_tp;
135 static ThreadPool async_io_tp;
136
137 static void async_invoke_thread (gpointer data);
138 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
139 static void threadpool_free_queue (ThreadPool *tp);
140 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
141 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
142 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
143 static void threadpool_start_idle_threads (ThreadPool *tp);
144 static void threadpool_kill_idle_threads (ThreadPool *tp);
145 static gboolean threadpool_start_thread (ThreadPool *tp);
146 static void monitor_thread (gpointer data);
147 static void socket_io_cleanup (SocketIOData *data);
148 static MonoObject *get_io_event (MonoMList **list, gint event);
149 static int get_events_from_list (MonoMList *list);
150 static int get_event_from_state (MonoSocketAsyncResult *state);
151
152 static MonoClass *async_call_klass;
153 static MonoClass *socket_async_call_klass;
154 static MonoClass *process_async_call_klass;
155
156 static GPtrArray *wsqs;
157 CRITICAL_SECTION wsqs_lock;
158
159 /* Hooks */
160 static MonoThreadPoolFunc tp_start_func;
161 static MonoThreadPoolFunc tp_finish_func;
162 static gpointer tp_hooks_user_data;
163 static MonoThreadPoolItemFunc tp_item_begin_func;
164 static MonoThreadPoolItemFunc tp_item_end_func;
165 static gpointer tp_item_user_data;
166
167 enum {
168         AIO_OP_FIRST,
169         AIO_OP_ACCEPT = 0,
170         AIO_OP_CONNECT,
171         AIO_OP_RECEIVE,
172         AIO_OP_RECEIVEFROM,
173         AIO_OP_SEND,
174         AIO_OP_SENDTO,
175         AIO_OP_RECV_JUST_CALLBACK,
176         AIO_OP_SEND_JUST_CALLBACK,
177         AIO_OP_READPIPE,
178         AIO_OP_CONSOLE2,
179         AIO_OP_DISCONNECT,
180         AIO_OP_ACCEPTRECEIVE,
181         AIO_OP_RECEIVE_BUFFERS,
182         AIO_OP_SEND_BUFFERS,
183         AIO_OP_LAST
184 };
185
186 #include <mono/metadata/tpool-poll.c>
187 #ifdef HAVE_EPOLL
188 #include <mono/metadata/tpool-epoll.c>
189 #elif defined(HAVE_KQUEUE)
190 #include <mono/metadata/tpool-kqueue.c>
191 #endif
192 /*
193  * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
194  * assemblies can be unloaded.
195  */
196
197 static gboolean
198 is_system_type (MonoDomain *domain, MonoClass *klass)
199 {
200         if (domain->system_image == NULL)
201                 domain->system_image = mono_image_loaded ("System");
202
203         return klass->image == domain->system_image;
204 }
205
206 static gboolean
207 is_corlib_type (MonoDomain *domain, MonoClass *klass)
208 {
209         return klass->image == mono_defaults.corlib;
210 }
211
212 /*
213  * Note that we call it is_socket_type() where 'socket' refers to the image
214  * that contains the System.Net.Sockets.Socket type.
215  * For moonlight there is a System.Net.Sockets.Socket class in both System.dll and System.Net.dll.
216 */
217 static gboolean
218 is_socket_type (MonoDomain *domain, MonoClass *klass)
219 {
220         static const char *version = NULL;
221         static gboolean moonlight;
222
223         if (is_system_type (domain, klass))
224                 return TRUE;
225
226         /* If moonlight, check if the type is in System.Net.dll too */
227         if (version == NULL) {
228                 version = mono_get_runtime_info ()->framework_version;
229                 moonlight = !strcmp (version, "2.1");
230         }
231
232         if (!moonlight)
233                 return FALSE;
234
235         if (domain->system_net_dll == NULL)
236                 domain->system_net_dll = mono_image_loaded ("System.Net");
237         
238         return klass->image == domain->system_net_dll;
239 }
240
241 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
242         if (*loc) \
243                 return *loc == _class; \
244         if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
245                 *loc = _class; \
246                 return TRUE; \
247         } \
248         return FALSE; \
249 } while (0) \
250
251 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
252
253 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
254
255 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
256
257 static gboolean
258 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
259 {
260         check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
261 }
262
263 static gboolean
264 is_socket (MonoDomain *domain, MonoClass *klass)
265 {
266         check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
267 }
268
269 static gboolean
270 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
271 {
272         return (klass->nested_in &&
273                         is_socket (domain, klass->nested_in) &&
274                         !strcmp (klass->name, "SocketAsyncResult"));
275 }
276
277 static gboolean
278 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
279 {
280         return (klass->nested_in &&
281                         is_socket (domain, klass->nested_in) &&
282                         !strcmp (klass->name, "SocketAsyncCall"));
283 }
284
285 static gboolean
286 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
287 {
288         check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
289 }
290
291 static gboolean
292 is_sd_process (MonoDomain *domain, MonoClass *klass)
293 {
294         check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
295 }
296
297 static gboolean
298 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
299 {
300
301         return (klass->nested_in &&
302                         is_sd_process (domain, klass->nested_in) &&
303                 !strcmp (klass->name, "AsyncReadHandler"));
304 }
305
306
307 #ifdef DISABLE_SOCKETS
308
309 #define socket_io_cleanup(x)
310
311 static int
312 get_event_from_state (MonoSocketAsyncResult *state)
313 {
314         g_assert_not_reached ();
315         return -1;
316 }
317
318 static int
319 get_events_from_list (MonoMList *list)
320 {
321         return 0;
322 }
323
324 #else
325
326 static void
327 socket_io_cleanup (SocketIOData *data)
328 {
329         EnterCriticalSection (&data->io_lock);
330         if (data->inited != 2) {
331                 LeaveCriticalSection (&data->io_lock);
332                 return;
333         }
334         data->inited = 3;
335         data->shutdown (data->event_data);
336         LeaveCriticalSection (&data->io_lock);
337 }
338
339 static int
340 get_event_from_state (MonoSocketAsyncResult *state)
341 {
342         switch (state->operation) {
343         case AIO_OP_ACCEPT:
344         case AIO_OP_RECEIVE:
345         case AIO_OP_RECV_JUST_CALLBACK:
346         case AIO_OP_RECEIVEFROM:
347         case AIO_OP_READPIPE:
348         case AIO_OP_ACCEPTRECEIVE:
349         case AIO_OP_RECEIVE_BUFFERS:
350                 return MONO_POLLIN;
351         case AIO_OP_SEND:
352         case AIO_OP_SEND_JUST_CALLBACK:
353         case AIO_OP_SENDTO:
354         case AIO_OP_CONNECT:
355         case AIO_OP_SEND_BUFFERS:
356         case AIO_OP_DISCONNECT:
357                 return MONO_POLLOUT;
358         default: /* Should never happen */
359                 g_message ("get_event_from_state: unknown value in switch!!!");
360                 return 0;
361         }
362 }
363
364 static int
365 get_events_from_list (MonoMList *list)
366 {
367         MonoSocketAsyncResult *state;
368         int events = 0;
369
370         while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
371                 events |= get_event_from_state (state);
372                 list = mono_mlist_next (list);
373         }
374
375         return events;
376 }
377
378 #define ICALL_RECV(x)   ves_icall_System_Net_Sockets_Socket_Receive_internal (\
379                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
380                                  x->socket_flags, &x->error);
381
382 #define ICALL_SEND(x)   ves_icall_System_Net_Sockets_Socket_Send_internal (\
383                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
384                                  x->socket_flags, &x->error);
385
386 #endif /* !DISABLE_SOCKETS */
387
388 static void
389 threadpool_jobs_inc (MonoObject *obj)
390 {
391         if (obj)
392                 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
393 }
394
395 static gboolean
396 threadpool_jobs_dec (MonoObject *obj)
397 {
398         MonoDomain *domain = obj->vtable->domain;
399         int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
400         if (remaining_jobs == 0 && domain->cleanup_semaphore) {
401                 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
402                 return TRUE;
403         }
404         return FALSE;
405 }
406
407 static MonoObject *
408 get_io_event (MonoMList **list, gint event)
409 {
410         MonoObject *state;
411         MonoMList *current;
412         MonoMList *prev;
413
414         current = *list;
415         prev = NULL;
416         state = NULL;
417         while (current) {
418                 state = mono_mlist_get_data (current);
419                 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
420                         break;
421
422                 state = NULL;
423                 prev = current;
424                 current = mono_mlist_next (current);
425         }
426
427         if (current) {
428                 if (prev) {
429                         mono_mlist_set_next (prev, mono_mlist_next (current));
430                 } else {
431                         *list = mono_mlist_next (*list);
432                 }
433         }
434
435         return state;
436 }
437
438 /*
439  * select/poll wake up when a socket is closed, but epoll just removes
440  * the socket from its internal list without notification.
441  */
442 void
443 mono_thread_pool_remove_socket (int sock)
444 {
445         MonoMList *list;
446         MonoSocketAsyncResult *state;
447         MonoObject *ares;
448
449         if (socket_io_data.inited == 0)
450                 return;
451
452         EnterCriticalSection (&socket_io_data.io_lock);
453         if (socket_io_data.sock_to_state == NULL) {
454                 LeaveCriticalSection (&socket_io_data.io_lock);
455                 return;
456         }
457         list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
458         if (list)
459                 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
460         LeaveCriticalSection (&socket_io_data.io_lock);
461         
462         while (list) {
463                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
464                 if (state->operation == AIO_OP_RECEIVE)
465                         state->operation = AIO_OP_RECV_JUST_CALLBACK;
466                 else if (state->operation == AIO_OP_SEND)
467                         state->operation = AIO_OP_SEND_JUST_CALLBACK;
468
469                 ares = get_io_event (&list, MONO_POLLIN);
470                 threadpool_append_job (&async_io_tp, ares);
471                 if (list) {
472                         ares = get_io_event (&list, MONO_POLLOUT);
473                         threadpool_append_job (&async_io_tp, ares);
474                 }
475         }
476 }
477
478 static void
479 init_event_system (SocketIOData *data)
480 {
481 #ifdef HAVE_EPOLL
482         if (data->event_system == EPOLL_BACKEND)
483                 data->event_data = tp_epoll_init (data);
484 #elif defined(HAVE_KQUEUE)
485         if (data->event_system == KQUEUE_BACKEND)
486                 data->event_data = tp_kqueue_init (data);
487 #endif
488         if (data->event_system == POLL_BACKEND)
489                 data->event_data = tp_poll_init (data);
490 }
491
492 static void
493 socket_io_init (SocketIOData *data)
494 {
495         int inited;
496
497         if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
498                 return;
499
500         inited = InterlockedCompareExchange (&data->inited, 1, 0);
501         if (inited >= 1) {
502                 while (TRUE) {
503                         if (data->inited >= 2)
504                                 return;
505                         SleepEx (1, FALSE);
506                 }
507         }
508
509         EnterCriticalSection (&data->io_lock);
510         data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
511 #ifdef HAVE_EPOLL
512         data->event_system = EPOLL_BACKEND;
513 #elif defined(HAVE_KQUEUE)
514         data->event_system = KQUEUE_BACKEND;
515 #else
516         data->event_system = POLL_BACKEND;
517 #endif
518         if (g_getenv ("MONO_DISABLE_AIO") != NULL)
519                 data->event_system = POLL_BACKEND;
520
521         init_event_system (data);
522         mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
523         LeaveCriticalSection (&data->io_lock);
524         data->inited = 2;
525         threadpool_start_thread (&async_io_tp);
526 }
527
528 static void
529 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
530 {
531         MonoMList *list;
532         SocketIOData *data = &socket_io_data;
533         int fd;
534         gboolean is_new;
535         int ievt;
536
537         socket_io_init (&socket_io_data);
538         if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
539                 return;
540         if (async_tp.pool_status == 2)
541                 return;
542
543         MONO_OBJECT_SETREF (state, ares, ares);
544
545         fd = GPOINTER_TO_INT (state->handle);
546         EnterCriticalSection (&data->io_lock);
547         if (data->sock_to_state == NULL) {
548                 LeaveCriticalSection (&data->io_lock);
549                 return;
550         }
551         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
552         if (list == NULL) {
553                 list = mono_mlist_alloc ((MonoObject*)state);
554                 is_new = TRUE;
555         } else {
556                 list = mono_mlist_append (list, (MonoObject*)state);
557                 is_new = FALSE;
558         }
559
560         mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
561         ievt = get_events_from_list (list);
562         LeaveCriticalSection (&data->io_lock);
563         data->modify (data->event_data, fd, state->operation, ievt, is_new);
564 }
565
566 #ifndef DISABLE_SOCKETS
567 static gboolean
568 socket_io_filter (MonoObject *target, MonoObject *state)
569 {
570         gint op;
571         MonoSocketAsyncResult *sock_res;
572         MonoClass *klass;
573         MonoDomain *domain;
574
575         if (target == NULL || state == NULL)
576                 return FALSE;
577
578         domain = target->vtable->domain;
579         klass = target->vtable->klass;
580         if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
581                 socket_async_call_klass = klass;
582
583         if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
584                 process_async_call_klass = klass;
585
586         if (klass != socket_async_call_klass && klass != process_async_call_klass)
587                 return FALSE;
588
589         sock_res = (MonoSocketAsyncResult *) state;
590         op = sock_res->operation;
591         if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
592                 return FALSE;
593
594         return TRUE;
595 }
596 #endif /* !DISABLE_SOCKETS */
597
598 /* Returns the exception thrown when invoking, if any */
599 static MonoObject *
600 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
601 {
602         ASyncCall *ac = (ASyncCall *)ares->object_data;
603         MonoObject *res, *exc = NULL;
604         MonoArray *out_args = NULL;
605         HANDLE wait_event = NULL;
606
607         if (ares->execution_context) {
608                 /* use captured ExecutionContext (if available) */
609                 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
610                 mono_thread_set_execution_context (ares->execution_context);
611         } else {
612                 ares->original_context = NULL;
613         }
614
615         if (ac == NULL) {
616                 /* Fast path from ThreadPool.*QueueUserWorkItem */
617                 void *pa = ares->async_state;
618                 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
619         } else {
620                 MonoObject *cb_exc = NULL;
621
622                 ac->msg->exc = NULL;
623                 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
624                 MONO_OBJECT_SETREF (ac, res, res);
625                 MONO_OBJECT_SETREF (ac, msg->exc, exc);
626                 MONO_OBJECT_SETREF (ac, out_args, out_args);
627
628                 mono_monitor_enter ((MonoObject *) ares);
629                 ares->completed = 1;
630                 if (ares->handle != NULL)
631                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
632                 mono_monitor_exit ((MonoObject *) ares);
633                 /* notify listeners */
634                 if (wait_event != NULL)
635                         SetEvent (wait_event);
636
637                 /* call async callback if cb_method != null*/
638                 if (ac != NULL && ac->cb_method) {
639                         void *pa = &ares;
640                         cb_exc = NULL;
641                         mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
642                         MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
643                         exc = cb_exc;
644                 } else {
645                         exc = NULL;
646                 }
647         }
648
649         /* restore original thread execution context if flow isn't suppressed, i.e. non null */
650         if (ares->original_context) {
651                 mono_thread_set_execution_context (ares->original_context);
652                 ares->original_context = NULL;
653         }
654         return exc;
655 }
656
657 static void
658 threadpool_start_idle_threads (ThreadPool *tp)
659 {
660         int n;
661         guint32 stack_size;
662
663         stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
664         do {
665                 while (1) {
666                         n = tp->nthreads;
667                         if (n >= tp->min_threads)
668                                 return;
669                         if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
670                                 break;
671                 }
672                 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
673                 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
674                 SleepEx (100, TRUE);
675         } while (1);
676 }
677
678 static void
679 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
680 {
681         memset (tp, 0, sizeof (ThreadPool));
682         tp->min_threads = min_threads;
683         tp->max_threads = max_threads;
684         tp->async_invoke = async_invoke;
685         tp->queue = mono_cq_create ();
686         MONO_SEM_INIT (&tp->new_job, 0);
687 }
688
689 static void *
690 init_perf_counter (const char *category, const char *counter)
691 {
692         MonoString *category_str;
693         MonoString *counter_str;
694         MonoString *machine;
695         MonoDomain *root;
696         MonoBoolean custom;
697         int type;
698
699         if (category == NULL || counter == NULL)
700                 return NULL;
701         root = mono_get_root_domain ();
702         category_str = mono_string_new (root, category);
703         counter_str = mono_string_new (root, counter);
704         machine = mono_string_new (root, ".");
705         return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
706 }
707
708 #ifdef DEBUG
709 static void
710 print_pool_info (ThreadPool *tp)
711 {
712
713 //      if (tp->tail - tp->head == 0)
714 //              return;
715
716         g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
717         g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
718         g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
719         g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
720         g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
721         g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
722         g_print ("Queued: %d\n", (tp->tail - tp->head));
723         if (tp == &async_tp) {
724                 int i;
725                 EnterCriticalSection (&wsqs_lock);
726                 for (i = 0; i < wsqs->len; i++) {
727                         g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
728                 }
729                 LeaveCriticalSection (&wsqs_lock);
730         } else {
731                 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
732         }
733         g_print ("-------------\n");
734 }
735
736 static void
737 signal_handler (int signo)
738 {
739         ThreadPool *tp;
740
741         tp = &async_tp;
742         g_print ("\n-----Non-IO-----\n");
743         print_pool_info (tp);
744         tp = &async_io_tp;
745         g_print ("\n-----IO-----\n");
746         print_pool_info (tp);
747         alarm (2);
748 }
749 #endif
750
751 static void
752 monitor_thread (gpointer unused)
753 {
754         ThreadPool *pools [2];
755         MonoInternalThread *thread;
756         guint32 ms;
757         gboolean need_one;
758         int i;
759
760         pools [0] = &async_tp;
761         pools [1] = &async_io_tp;
762         thread = mono_thread_internal_current ();
763         ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
764         while (1) {
765                 ms = 500;
766                 do {
767                         guint32 ts;
768                         ts = mono_msec_ticks ();
769                         if (SleepEx (ms, TRUE) == 0)
770                                 break;
771                         ms -= (mono_msec_ticks () - ts);
772                         if (mono_runtime_is_shutting_down ())
773                                 break;
774                         if (THREAD_WANTS_A_BREAK (thread))
775                                 mono_thread_interruption_checkpoint ();
776                 } while (ms > 0);
777
778                 if (mono_runtime_is_shutting_down ())
779                         break;
780
781                 for (i = 0; i < 2; i++) {
782                         ThreadPool *tp;
783                         tp = pools [i];
784                         if (tp->waiting > 0)
785                                 continue;
786                         need_one = (mono_cq_count (tp->queue) > 0);
787                         if (!need_one && !tp->is_io) {
788                                 EnterCriticalSection (&wsqs_lock);
789                                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
790                                         MonoWSQ *wsq;
791                                         wsq = g_ptr_array_index (wsqs, i);
792                                         if (mono_wsq_count (wsq) != 0) {
793                                                 need_one = TRUE;
794                                                 break;
795                                         }
796                                 }
797                                 LeaveCriticalSection (&wsqs_lock);
798                         }
799                         if (need_one)
800                                 threadpool_start_thread (tp);
801                 }
802         }
803 }
804
805 void
806 mono_thread_pool_init ()
807 {
808         gint threads_per_cpu = 1;
809         gint thread_count;
810         gint cpu_count = mono_cpu_count ();
811         int result;
812
813         if (tp_inited == 2)
814                 return;
815
816         result = InterlockedCompareExchange (&tp_inited, 1, 0);
817         if (result == 1) {
818                 while (1) {
819                         SleepEx (1, FALSE);
820                         if (tp_inited == 2)
821                                 return;
822                 }
823         }
824
825         MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
826         InitializeCriticalSection (&socket_io_data.io_lock);
827         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
828                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
829                 if (threads_per_cpu < 1)
830                         threads_per_cpu = 1;
831         }
832
833         thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
834         threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
835         threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
836         async_io_tp.is_io = TRUE;
837
838         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
839         g_assert (async_call_klass);
840
841         InitializeCriticalSection (&wsqs_lock);
842         wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
843         mono_wsq_init ();
844
845         async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
846         g_assert (async_tp.pc_nitems);
847
848         async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
849         g_assert (async_io_tp.pc_nitems);
850
851         async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
852         g_assert (async_tp.pc_nthreads);
853
854         async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
855         g_assert (async_io_tp.pc_nthreads);
856         tp_inited = 2;
857 #ifdef DEBUG
858         signal (SIGALRM, signal_handler);
859         alarm (2);
860 #endif
861 }
862
863 static MonoAsyncResult *
864 create_simple_asyncresult (MonoObject *target, MonoObject *state)
865 {
866         MonoDomain *domain = mono_domain_get ();
867         MonoAsyncResult *ares;
868
869         /* Don't call mono_async_result_new() to avoid capturing the context */
870         ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
871         MONO_OBJECT_SETREF (ares, async_delegate, target);
872         MONO_OBJECT_SETREF (ares, async_state, state);
873         return ares;
874 }
875
876 void
877 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
878 {
879         MonoAsyncResult *ares;
880
881         ares = create_simple_asyncresult (target, (MonoObject *) state);
882         socket_io_add (ares, state);
883 }
884
885 MonoAsyncResult *
886 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
887                       MonoObject *state)
888 {
889         MonoDomain *domain = mono_domain_get ();
890         MonoAsyncResult *ares;
891         ASyncCall *ac;
892
893         ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
894         MONO_OBJECT_SETREF (ac, msg, msg);
895         MONO_OBJECT_SETREF (ac, state, state);
896
897         if (async_callback) {
898                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
899                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
900         }
901
902         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
903         MONO_OBJECT_SETREF (ares, async_delegate, target);
904
905 #ifndef DISABLE_SOCKETS
906         if (socket_io_filter (target, state)) {
907                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
908                 return ares;
909         }
910 #endif
911         threadpool_append_job (&async_tp, (MonoObject *) ares);
912         return ares;
913 }
914
915 MonoObject *
916 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
917 {
918         ASyncCall *ac;
919         HANDLE wait_event;
920
921         *exc = NULL;
922         *out_args = NULL;
923
924         /* check if already finished */
925         mono_monitor_enter ((MonoObject *) ares);
926         
927         if (ares->endinvoke_called) {
928                 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
929                 mono_monitor_exit ((MonoObject *) ares);
930                 return NULL;
931         }
932
933         ares->endinvoke_called = 1;
934         /* wait until we are really finished */
935         if (!ares->completed) {
936                 if (ares->handle == NULL) {
937                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
938                         g_assert(wait_event != 0);
939                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
940                 } else {
941                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
942                 }
943                 mono_monitor_exit ((MonoObject *) ares);
944                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
945         } else {
946                 mono_monitor_exit ((MonoObject *) ares);
947         }
948
949         ac = (ASyncCall *) ares->object_data;
950         g_assert (ac != NULL);
951         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
952         *out_args = ac->out_args;
953
954         return ac->res;
955 }
956
957 static void
958 threadpool_kill_idle_threads (ThreadPool *tp)
959 {
960         gint n;
961
962         n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
963         while (n) {
964                 n--;
965                 MONO_SEM_POST (&tp->new_job);
966         }
967 }
968
969 void
970 mono_thread_pool_cleanup (void)
971 {
972         if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
973                 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
974                 threadpool_kill_idle_threads (&async_io_tp);
975         }
976
977         if (async_io_tp.queue != NULL) {
978                 MONO_SEM_DESTROY (&async_io_tp.new_job);
979                 threadpool_free_queue (&async_io_tp);
980         }
981
982
983         if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
984                 threadpool_kill_idle_threads (&async_tp);
985                 threadpool_free_queue (&async_tp);
986         }
987
988         if (wsqs) {
989                 EnterCriticalSection (&wsqs_lock);
990                 mono_wsq_cleanup ();
991                 if (wsqs)
992                         g_ptr_array_free (wsqs, TRUE);
993                 wsqs = NULL;
994                 LeaveCriticalSection (&wsqs_lock);
995                 MONO_SEM_DESTROY (&async_tp.new_job);
996         }
997 }
998
999 static gboolean
1000 threadpool_start_thread (ThreadPool *tp)
1001 {
1002         gint n;
1003         guint32 stack_size;
1004
1005         stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1006         while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1007                 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1008                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1009                         mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1010                         return TRUE;
1011                 }
1012         }
1013
1014         return FALSE;
1015 }
1016
1017 static void
1018 pulse_on_new_job (ThreadPool *tp)
1019 {
1020         if (tp->waiting)
1021                 MONO_SEM_POST (&tp->new_job);
1022 }
1023
1024 void
1025 icall_append_job (MonoObject *ar)
1026 {
1027         threadpool_append_jobs (&async_tp, &ar, 1);
1028 }
1029
1030 static void
1031 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1032 {
1033         threadpool_append_jobs (tp, &ar, 1);
1034 }
1035
1036 static void
1037 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1038 {
1039         static int job_counter;
1040         MonoObject *ar;
1041         gint i;
1042
1043         if (mono_runtime_is_shutting_down ())
1044                 return;
1045
1046         if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1047                 if (!tp->is_io)
1048                         mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1049                 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1050                  * the threadpool that much
1051                 * mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1052                 */
1053         }
1054
1055         for (i = 0; i < njobs; i++) {
1056                 ar = jobs [i];
1057                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1058                         continue; /* Might happen when cleaning domain jobs */
1059                 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1060                         MonoAsyncResult *o = (MonoAsyncResult *) ar;
1061                         o->add_time = mono_100ns_ticks ();
1062                 }
1063                 threadpool_jobs_inc (ar); 
1064                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1065                 if (!tp->is_io && mono_wsq_local_push (ar))
1066                         continue;
1067
1068                 mono_cq_enqueue (tp->queue, ar);
1069         }
1070
1071         for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1072                 pulse_on_new_job (tp);
1073 }
1074
1075 static void
1076 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1077 {
1078         MonoObject *obj;
1079         MonoMList *other;
1080
1081         other = NULL;
1082         while (mono_cq_dequeue (tp->queue, &obj)) {
1083                 if (obj == NULL)
1084                         continue;
1085                 if (obj->vtable->domain != domain)
1086                         other = mono_mlist_prepend (other, obj);
1087                 threadpool_jobs_dec (obj);
1088         }
1089
1090         while (other) {
1091                 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1092                 other = mono_mlist_next (other);
1093         }
1094 }
1095
1096 /*
1097  * Clean up the threadpool of all domain jobs.
1098  * Can only be called as part of the domain unloading process as
1099  * it will wait for all jobs to be visible to the interruption code. 
1100  */
1101 gboolean
1102 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1103 {
1104         HANDLE sem_handle;
1105         int result = TRUE;
1106         guint32 start_time = 0;
1107
1108         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1109
1110         threadpool_clear_queue (&async_tp, domain);
1111         threadpool_clear_queue (&async_io_tp, domain);
1112
1113         /*
1114          * There might be some threads out that could be about to execute stuff from the given domain.
1115          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1116          */
1117         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1118
1119         domain->cleanup_semaphore = sem_handle;
1120         /*
1121          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1122          * and reading threadpool_jobs.
1123          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1124          */
1125         mono_memory_write_barrier ();
1126
1127         if (domain->threadpool_jobs && timeout != -1)
1128                 start_time = mono_msec_ticks ();
1129         while (domain->threadpool_jobs) {
1130                 WaitForSingleObject (sem_handle, timeout);
1131                 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1132                         result = FALSE;
1133                         break;
1134                 }
1135         }
1136
1137         domain->cleanup_semaphore = NULL;
1138         CloseHandle (sem_handle);
1139         return result;
1140 }
1141
1142 static void
1143 threadpool_free_queue (ThreadPool *tp)
1144 {
1145         mono_cq_destroy (tp->queue);
1146         tp->queue = NULL;
1147 }
1148
1149 gboolean
1150 mono_thread_pool_is_queue_array (MonoArray *o)
1151 {
1152         // gpointer obj = o;
1153
1154         // FIXME: need some fix in sgen code.
1155         return FALSE;
1156 }
1157
1158 static MonoWSQ *
1159 add_wsq (void)
1160 {
1161         int i;
1162         MonoWSQ *wsq;
1163
1164         EnterCriticalSection (&wsqs_lock);
1165         wsq = mono_wsq_create ();
1166         if (wsqs == NULL) {
1167                 LeaveCriticalSection (&wsqs_lock);
1168                 return NULL;
1169         }
1170         for (i = 0; i < wsqs->len; i++) {
1171                 if (g_ptr_array_index (wsqs, i) == NULL) {
1172                         wsqs->pdata [i] = wsq;
1173                         LeaveCriticalSection (&wsqs_lock);
1174                         return wsq;
1175                 }
1176         }
1177         g_ptr_array_add (wsqs, wsq);
1178         LeaveCriticalSection (&wsqs_lock);
1179         return wsq;
1180 }
1181
1182 static void
1183 remove_wsq (MonoWSQ *wsq)
1184 {
1185         gpointer data;
1186
1187         if (wsq == NULL)
1188                 return;
1189
1190         EnterCriticalSection (&wsqs_lock);
1191         if (wsqs == NULL) {
1192                 LeaveCriticalSection (&wsqs_lock);
1193                 return;
1194         }
1195         g_ptr_array_remove_fast (wsqs, wsq);
1196         data = NULL;
1197         /*
1198          * Only clean this up when shutting down, any other case will error out
1199          * if we're removing a queue that still has work items.
1200          */
1201         if (mono_runtime_is_shutting_down ()) {
1202                 while (mono_wsq_local_pop (&data)) {
1203                         threadpool_jobs_dec (data);
1204                         data = NULL;
1205                 }
1206         }
1207         mono_wsq_destroy (wsq);
1208         LeaveCriticalSection (&wsqs_lock);
1209 }
1210
1211 static void
1212 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1213 {
1214         int i;
1215         int ms;
1216
1217         if (wsqs == NULL || data == NULL || *data != NULL)
1218                 return;
1219
1220         ms = 0;
1221         do {
1222                 if (mono_runtime_is_shutting_down ())
1223                         return;
1224
1225                 EnterCriticalSection (&wsqs_lock);
1226                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1227                         MonoWSQ *wsq;
1228
1229                         wsq = wsqs->pdata [i];
1230                         if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1231                                 continue;
1232                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1233                         if (*data != NULL) {
1234                                 LeaveCriticalSection (&wsqs_lock);
1235                                 return;
1236                         }
1237                 }
1238                 LeaveCriticalSection (&wsqs_lock);
1239                 ms += 10;
1240         } while (retry && ms < 11);
1241 }
1242
1243 static gboolean
1244 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1245 {
1246         if (mono_runtime_is_shutting_down ())
1247                 return FALSE;
1248         mono_cq_dequeue (tp->queue, (MonoObject **) data);
1249         if (!tp->is_io && !*data)
1250                 try_steal (local_wsq, data, FALSE);
1251         return (*data != NULL);
1252 }
1253
1254 static void
1255 process_idle_times (ThreadPool *tp, gint64 t)
1256 {
1257         gint64 ticks;
1258         gint64 avg;
1259         gboolean compute_avg;
1260         gint new_threads;
1261         gint64 per1;
1262
1263         if (tp->ignore_times || t <= 0)
1264                 return;
1265
1266         compute_avg = FALSE;
1267         ticks = mono_100ns_ticks ();
1268         t = ticks - t;
1269         SPIN_LOCK (tp->sp_lock);
1270         if (tp->ignore_times) {
1271                 SPIN_UNLOCK (tp->sp_lock);
1272                 return;
1273         }
1274         tp->time_sum += t;
1275         tp->n_sum++;
1276         if (tp->last_check == 0)
1277                 tp->last_check = ticks;
1278         else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1279                 tp->ignore_times = 1;
1280                 compute_avg = TRUE;
1281         }
1282         SPIN_UNLOCK (tp->sp_lock);
1283
1284         if (!compute_avg)
1285                 return;
1286
1287         //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1288         tp->last_check = ticks;
1289         new_threads = 0;
1290         avg = tp->time_sum / tp->n_sum;
1291         if (tp->averages [1] == 0) {
1292                 tp->averages [1] = avg;
1293         } else {
1294                 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1295                 if (per1 > 5) {
1296                         if (avg > tp->averages [1]) {
1297                                 if (tp->averages [1] < tp->averages [0]) {
1298                                         new_threads = -1;
1299                                 } else {
1300                                         new_threads = 1;
1301                                 }
1302                         } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1303                                 new_threads = 1;
1304                         }
1305                 } else {
1306                         int min, n;
1307                         min = tp->min_threads;
1308                         n = tp->nthreads;
1309                         if ((n - min) < min && tp->busy_threads == n)
1310                                 new_threads = 1;
1311                 }
1312                 /*
1313                 if (new_threads != 0) {
1314                         printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1315                 }
1316                 */
1317         }
1318
1319         tp->time_sum = 0;
1320         tp->n_sum = 0;
1321
1322         tp->averages [0] = tp->averages [1];
1323         tp->averages [1] = avg;
1324         tp->ignore_times = 0;
1325
1326         if (new_threads == -1) {
1327                 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1328                         pulse_on_new_job (tp);
1329         }
1330 }
1331
1332 static gboolean
1333 should_i_die (ThreadPool *tp)
1334 {
1335         gboolean result = FALSE;
1336         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1337                 result = (tp->nthreads > tp->min_threads);
1338         return result;
1339 }
1340
1341 static void
1342 async_invoke_thread (gpointer data)
1343 {
1344         MonoDomain *domain;
1345         MonoInternalThread *thread;
1346         MonoWSQ *wsq;
1347         ThreadPool *tp;
1348         gboolean must_die;
1349         const gchar *name;
1350   
1351         tp = data;
1352         wsq = NULL;
1353         if (!tp->is_io)
1354                 wsq = add_wsq ();
1355
1356         thread = mono_thread_internal_current ();
1357
1358         mono_profiler_thread_start (thread->tid);
1359         name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1360         ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), name));
1361
1362         if (tp_start_func)
1363                 tp_start_func (tp_hooks_user_data);
1364
1365         data = NULL;
1366         for (;;) {
1367                 MonoAsyncResult *ar;
1368                 MonoClass *klass;
1369                 gboolean is_io_task;
1370                 gboolean is_socket;
1371                 int n_naps = 0;
1372
1373                 is_io_task = FALSE;
1374                 ar = (MonoAsyncResult *) data;
1375                 if (ar) {
1376                         InterlockedIncrement (&tp->busy_threads);
1377                         domain = ((MonoObject *)ar)->vtable->domain;
1378 #ifndef DISABLE_SOCKETS
1379                         klass = ((MonoObject *) data)->vtable->klass;
1380                         is_io_task = !is_corlib_asyncresult (domain, klass);
1381                         is_socket = FALSE;
1382                         if (is_io_task) {
1383                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1384                                 is_socket = is_socketasyncresult (domain, klass);
1385                                 ar = state->ares;
1386                                 switch (state->operation) {
1387                                 case AIO_OP_RECEIVE:
1388                                         state->total = ICALL_RECV (state);
1389                                         break;
1390                                 case AIO_OP_SEND:
1391                                         state->total = ICALL_SEND (state);
1392                                         break;
1393                                 }
1394                         }
1395 #endif
1396                         /* worker threads invokes methods in different domains,
1397                          * so we need to set the right domain here */
1398                         g_assert (domain);
1399
1400                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1401                                 threadpool_jobs_dec ((MonoObject *)ar);
1402                                 data = NULL;
1403                                 ar = NULL;
1404                                 InterlockedDecrement (&tp->busy_threads);
1405                         } else {
1406                                 mono_thread_push_appdomain_ref (domain);
1407                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1408                                         data = NULL;
1409                                         ar = NULL;
1410                                         mono_thread_pop_appdomain_ref ();
1411                                         InterlockedDecrement (&tp->busy_threads);
1412                                         continue;
1413                                 }
1414
1415                                 if (mono_domain_set (domain, FALSE)) {
1416                                         MonoObject *exc;
1417
1418                                         if (tp_item_begin_func)
1419                                                 tp_item_begin_func (tp_item_user_data);
1420
1421                                         if (!is_io_task && ar->add_time > 0)
1422                                                 process_idle_times (tp, ar->add_time);
1423                                         exc = mono_async_invoke (tp, ar);
1424                                         if (tp_item_end_func)
1425                                                 tp_item_end_func (tp_item_user_data);
1426                                         if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1427                                                 gboolean unloaded;
1428                                                 MonoClass *klass;
1429
1430                                                 klass = exc->vtable->klass;
1431                                                 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1432                                                 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1433                                                         mono_unhandled_exception (exc);
1434                                                         exit (255);
1435                                                 }
1436                                                 if (klass == mono_defaults.threadabortexception_class)
1437                                                         mono_thread_internal_reset_abort (thread);
1438                                         }
1439                                         if (is_socket && tp->is_io) {
1440                                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1441
1442                                                 if (state->completed && state->callback) {
1443                                                         MonoAsyncResult *cb_ares;
1444                                                         cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1445                                                                                                 (MonoObject *) state);
1446                                                         icall_append_job ((MonoObject *) cb_ares);
1447                                                 }
1448                                         }
1449                                         mono_domain_set (mono_get_root_domain (), TRUE);
1450                                 }
1451                                 mono_thread_pop_appdomain_ref ();
1452                                 InterlockedDecrement (&tp->busy_threads);
1453                                 /* If the callee changes the background status, set it back to TRUE */
1454                                 mono_thread_clr_state (thread , ~ThreadState_Background);
1455                                 if (!mono_thread_test_state (thread , ThreadState_Background))
1456                                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1457                         }
1458                 }
1459
1460                 ar = NULL;
1461                 data = NULL;
1462                 must_die = should_i_die (tp);
1463                 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1464                         dequeue_or_steal (tp, &data, wsq);
1465
1466                 n_naps = 0;
1467                 while (!must_die && !data && n_naps < 4) {
1468                         gboolean res;
1469
1470                         InterlockedIncrement (&tp->waiting);
1471 #if defined(__OpenBSD__)
1472                         while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1473 #else
1474                         while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1475 #endif
1476                                 if (mono_runtime_is_shutting_down ())
1477                                         break;
1478                                 if (THREAD_WANTS_A_BREAK (thread))
1479                                         mono_thread_interruption_checkpoint ();
1480                         }
1481                         InterlockedDecrement (&tp->waiting);
1482                         if (mono_runtime_is_shutting_down ())
1483                                 break;
1484                         must_die = should_i_die (tp);
1485                         dequeue_or_steal (tp, &data, wsq);
1486                         n_naps++;
1487                 }
1488
1489                 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1490                         mono_wsq_local_pop (&data);
1491                         if (data && must_die) {
1492                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1493                                 pulse_on_new_job (tp);
1494                         }
1495                 }
1496
1497                 if (!data) {
1498                         gint nt;
1499                         gboolean down;
1500                         while (1) {
1501                                 nt = tp->nthreads;
1502                                 down = mono_runtime_is_shutting_down ();
1503                                 if (!down && nt <= tp->min_threads)
1504                                         break;
1505                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1506                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1507                                         if (!tp->is_io) {
1508                                                 remove_wsq (wsq);
1509                                         }
1510
1511                                         mono_profiler_thread_end (thread->tid);
1512
1513                                         if (tp_finish_func)
1514                                                 tp_finish_func (tp_hooks_user_data);
1515                                         return;
1516                                 }
1517                         }
1518                 }
1519         }
1520
1521         g_assert_not_reached ();
1522 }
1523
1524 void
1525 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1526 {
1527         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1528         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1529 }
1530
1531 void
1532 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1533 {
1534         *workerThreads = async_tp.max_threads;
1535         *completionPortThreads = async_io_tp.max_threads;
1536 }
1537
1538 void
1539 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1540 {
1541         *workerThreads = async_tp.min_threads;
1542         *completionPortThreads = async_io_tp.min_threads;
1543 }
1544
1545 MonoBoolean
1546 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1547 {
1548         gint max_threads;
1549         gint max_io_threads;
1550
1551         max_threads = async_tp.max_threads;
1552         if (workerThreads <= 0 || workerThreads > max_threads)
1553                 return FALSE;
1554
1555         max_io_threads = async_io_tp.max_threads;
1556         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1557                 return FALSE;
1558
1559         InterlockedExchange (&async_tp.min_threads, workerThreads);
1560         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1561         if (workerThreads > async_tp.nthreads)
1562                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1563         if (completionPortThreads > async_io_tp.nthreads)
1564                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1565         return TRUE;
1566 }
1567
1568 MonoBoolean
1569 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1570 {
1571         gint min_threads;
1572         gint min_io_threads;
1573         gint cpu_count;
1574
1575         cpu_count = mono_cpu_count ();
1576         min_threads = async_tp.min_threads;
1577         if (workerThreads < min_threads || workerThreads < cpu_count)
1578                 return FALSE;
1579
1580         /* We don't really have the concept of completion ports. Do we care here? */
1581         min_io_threads = async_io_tp.min_threads;
1582         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1583                 return FALSE;
1584
1585         InterlockedExchange (&async_tp.max_threads, workerThreads);
1586         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1587         return TRUE;
1588 }
1589
1590 /**
1591  * mono_install_threadpool_thread_hooks
1592  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1593  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1594  * @user_data: argument passed to @start_func and @finish_func.
1595  *
1596  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1597  * The calls will be made from the thread itself.
1598  */
1599 void
1600 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1601 {
1602         tp_start_func = start_func;
1603         tp_finish_func = finish_func;
1604         tp_hooks_user_data = user_data;
1605 }
1606
1607 /**
1608  * mono_install_threadpool_item_hooks
1609  * @begin_func: the function to be called before a threadpool work item processing starts.
1610  * @end_func: the function to be called after a threadpool work item is finished.
1611  * @user_data: argument passed to @begin_func and @end_func.
1612  *
1613  * The calls will be made from the thread itself and from the same AppDomain
1614  * where the work item was executed.
1615  *
1616  */
1617 void
1618 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1619 {
1620         tp_item_begin_func = begin_func;
1621         tp_item_end_func = end_func;
1622         tp_item_user_data = user_data;
1623 }
1624