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