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