Merge pull request #495 from nicolas-raoul/fix-for-issue2907-with-no-formatting-changes
[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(USE_KQUEUE_FOR_THREADPOOL)
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 */
219 static gboolean
220 is_socket_type (MonoDomain *domain, MonoClass *klass)
221 {
222         return is_system_type (domain, klass);
223 }
224
225 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
226         if (*loc) \
227                 return *loc == _class; \
228         if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
229                 *loc = _class; \
230                 return TRUE; \
231         } \
232         return FALSE; \
233 } while (0) \
234
235 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
236
237 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
238
239 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
240
241 static gboolean
242 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
243 {
244         check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
245 }
246
247 static gboolean
248 is_socket (MonoDomain *domain, MonoClass *klass)
249 {
250         check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
251 }
252
253 static gboolean
254 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
255 {
256         return (klass->nested_in &&
257                         is_socket (domain, klass->nested_in) &&
258                         !strcmp (klass->name, "SocketAsyncResult"));
259 }
260
261 static gboolean
262 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
263 {
264         return (klass->nested_in &&
265                         is_socket (domain, klass->nested_in) &&
266                         !strcmp (klass->name, "SocketAsyncCall"));
267 }
268
269 static gboolean
270 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
271 {
272         check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
273 }
274
275 static gboolean
276 is_sd_process (MonoDomain *domain, MonoClass *klass)
277 {
278         check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
279 }
280
281 static gboolean
282 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
283 {
284
285         return (klass->nested_in &&
286                         is_sd_process (domain, klass->nested_in) &&
287                 !strcmp (klass->name, "AsyncReadHandler"));
288 }
289
290
291 #ifdef DISABLE_SOCKETS
292
293 #define socket_io_cleanup(x)
294
295 static int
296 get_event_from_state (MonoSocketAsyncResult *state)
297 {
298         g_assert_not_reached ();
299         return -1;
300 }
301
302 static int
303 get_events_from_list (MonoMList *list)
304 {
305         return 0;
306 }
307
308 #else
309
310 static void
311 socket_io_cleanup (SocketIOData *data)
312 {
313         EnterCriticalSection (&data->io_lock);
314         if (data->inited != 2) {
315                 LeaveCriticalSection (&data->io_lock);
316                 return;
317         }
318         data->inited = 3;
319         data->shutdown (data->event_data);
320         LeaveCriticalSection (&data->io_lock);
321 }
322
323 static int
324 get_event_from_state (MonoSocketAsyncResult *state)
325 {
326         switch (state->operation) {
327         case AIO_OP_ACCEPT:
328         case AIO_OP_RECEIVE:
329         case AIO_OP_RECV_JUST_CALLBACK:
330         case AIO_OP_RECEIVEFROM:
331         case AIO_OP_READPIPE:
332         case AIO_OP_ACCEPTRECEIVE:
333         case AIO_OP_RECEIVE_BUFFERS:
334                 return MONO_POLLIN;
335         case AIO_OP_SEND:
336         case AIO_OP_SEND_JUST_CALLBACK:
337         case AIO_OP_SENDTO:
338         case AIO_OP_CONNECT:
339         case AIO_OP_SEND_BUFFERS:
340         case AIO_OP_DISCONNECT:
341                 return MONO_POLLOUT;
342         default: /* Should never happen */
343                 g_message ("get_event_from_state: unknown value in switch!!!");
344                 return 0;
345         }
346 }
347
348 static int
349 get_events_from_list (MonoMList *list)
350 {
351         MonoSocketAsyncResult *state;
352         int events = 0;
353
354         while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
355                 events |= get_event_from_state (state);
356                 list = mono_mlist_next (list);
357         }
358
359         return events;
360 }
361
362 #define ICALL_RECV(x)   ves_icall_System_Net_Sockets_Socket_Receive_internal (\
363                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
364                                  x->socket_flags, &x->error);
365
366 #define ICALL_SEND(x)   ves_icall_System_Net_Sockets_Socket_Send_internal (\
367                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
368                                  x->socket_flags, &x->error);
369
370 #endif /* !DISABLE_SOCKETS */
371
372 static void
373 threadpool_jobs_inc (MonoObject *obj)
374 {
375         if (obj)
376                 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
377 }
378
379 static gboolean
380 threadpool_jobs_dec (MonoObject *obj)
381 {
382         MonoDomain *domain;
383         int remaining_jobs;
384
385         if (obj == NULL)
386                 return FALSE;
387
388         domain = obj->vtable->domain;
389         remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
390         if (remaining_jobs == 0 && domain->cleanup_semaphore) {
391                 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
392                 return TRUE;
393         }
394         return FALSE;
395 }
396
397 static MonoObject *
398 get_io_event (MonoMList **list, gint event)
399 {
400         MonoObject *state;
401         MonoMList *current;
402         MonoMList *prev;
403
404         current = *list;
405         prev = NULL;
406         state = NULL;
407         while (current) {
408                 state = mono_mlist_get_data (current);
409                 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
410                         break;
411
412                 state = NULL;
413                 prev = current;
414                 current = mono_mlist_next (current);
415         }
416
417         if (current) {
418                 if (prev) {
419                         mono_mlist_set_next (prev, mono_mlist_next (current));
420                 } else {
421                         *list = mono_mlist_next (*list);
422                 }
423         }
424
425         return state;
426 }
427
428 /*
429  * select/poll wake up when a socket is closed, but epoll just removes
430  * the socket from its internal list without notification.
431  */
432 void
433 mono_thread_pool_remove_socket (int sock)
434 {
435         MonoMList *list;
436         MonoSocketAsyncResult *state;
437         MonoObject *ares;
438
439         if (socket_io_data.inited == 0)
440                 return;
441
442         EnterCriticalSection (&socket_io_data.io_lock);
443         if (socket_io_data.sock_to_state == NULL) {
444                 LeaveCriticalSection (&socket_io_data.io_lock);
445                 return;
446         }
447         list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
448         if (list)
449                 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
450         LeaveCriticalSection (&socket_io_data.io_lock);
451         
452         while (list) {
453                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
454                 if (state->operation == AIO_OP_RECEIVE)
455                         state->operation = AIO_OP_RECV_JUST_CALLBACK;
456                 else if (state->operation == AIO_OP_SEND)
457                         state->operation = AIO_OP_SEND_JUST_CALLBACK;
458
459                 ares = get_io_event (&list, MONO_POLLIN);
460                 threadpool_append_job (&async_io_tp, ares);
461                 if (list) {
462                         ares = get_io_event (&list, MONO_POLLOUT);
463                         threadpool_append_job (&async_io_tp, ares);
464                 }
465         }
466 }
467
468 static void
469 init_event_system (SocketIOData *data)
470 {
471 #ifdef HAVE_EPOLL
472         if (data->event_system == EPOLL_BACKEND) {
473                 data->event_data = tp_epoll_init (data);
474                 if (data->event_data == NULL) {
475                         if (g_getenv ("MONO_DEBUG"))
476                                 g_message ("Falling back to poll()");
477                         data->event_system = POLL_BACKEND;
478                 }
479         }
480 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
481         if (data->event_system == KQUEUE_BACKEND)
482                 data->event_data = tp_kqueue_init (data);
483 #endif
484         if (data->event_system == POLL_BACKEND)
485                 data->event_data = tp_poll_init (data);
486 }
487
488 static void
489 socket_io_init (SocketIOData *data)
490 {
491         int inited;
492
493         if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
494                 return;
495
496         inited = InterlockedCompareExchange (&data->inited, 1, 0);
497         if (inited >= 1) {
498                 while (TRUE) {
499                         if (data->inited >= 2)
500                                 return;
501                         SleepEx (1, FALSE);
502                 }
503         }
504
505         EnterCriticalSection (&data->io_lock);
506         data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
507 #ifdef HAVE_EPOLL
508         data->event_system = EPOLL_BACKEND;
509 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
510         data->event_system = KQUEUE_BACKEND;
511 #else
512         data->event_system = POLL_BACKEND;
513 #endif
514         if (g_getenv ("MONO_DISABLE_AIO") != NULL)
515                 data->event_system = POLL_BACKEND;
516
517         init_event_system (data);
518         mono_thread_create_internal (mono_get_root_domain (), data->wait, data, TRUE, SMALL_STACK);
519         LeaveCriticalSection (&data->io_lock);
520         data->inited = 2;
521         threadpool_start_thread (&async_io_tp);
522 }
523
524 static void
525 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
526 {
527         MonoMList *list;
528         SocketIOData *data = &socket_io_data;
529         int fd;
530         gboolean is_new;
531         int ievt;
532
533         socket_io_init (&socket_io_data);
534         if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
535                 return;
536         if (async_tp.pool_status == 2)
537                 return;
538
539         MONO_OBJECT_SETREF (state, ares, ares);
540
541         fd = GPOINTER_TO_INT (state->handle);
542         EnterCriticalSection (&data->io_lock);
543         if (data->sock_to_state == NULL) {
544                 LeaveCriticalSection (&data->io_lock);
545                 return;
546         }
547         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
548         if (list == NULL) {
549                 list = mono_mlist_alloc ((MonoObject*)state);
550                 is_new = TRUE;
551         } else {
552                 list = mono_mlist_append (list, (MonoObject*)state);
553                 is_new = FALSE;
554         }
555
556         mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
557         ievt = get_events_from_list (list);
558         LeaveCriticalSection (&data->io_lock);
559         data->modify (data->event_data, fd, state->operation, ievt, is_new);
560 }
561
562 #ifndef DISABLE_SOCKETS
563 static gboolean
564 socket_io_filter (MonoObject *target, MonoObject *state)
565 {
566         gint op;
567         MonoSocketAsyncResult *sock_res;
568         MonoClass *klass;
569         MonoDomain *domain;
570
571         if (target == NULL || state == NULL)
572                 return FALSE;
573
574         domain = target->vtable->domain;
575         klass = target->vtable->klass;
576         if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
577                 socket_async_call_klass = klass;
578
579         if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
580                 process_async_call_klass = klass;
581
582         if (klass != socket_async_call_klass && klass != process_async_call_klass)
583                 return FALSE;
584
585         sock_res = (MonoSocketAsyncResult *) state;
586         op = sock_res->operation;
587         if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
588                 return FALSE;
589
590         return TRUE;
591 }
592 #endif /* !DISABLE_SOCKETS */
593
594 /* Returns the exception thrown when invoking, if any */
595 static MonoObject *
596 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
597 {
598         ASyncCall *ac = (ASyncCall *)ares->object_data;
599         MonoObject *res, *exc = NULL;
600         MonoArray *out_args = NULL;
601         HANDLE wait_event = NULL;
602
603         if (ares->execution_context) {
604                 /* use captured ExecutionContext (if available) */
605                 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
606                 mono_thread_set_execution_context (ares->execution_context);
607         } else {
608                 ares->original_context = NULL;
609         }
610
611         if (ac == NULL) {
612                 /* Fast path from ThreadPool.*QueueUserWorkItem */
613                 void *pa = ares->async_state;
614                 res = mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
615         } else {
616                 MonoObject *cb_exc = NULL;
617
618                 ac->msg->exc = NULL;
619                 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
620                 MONO_OBJECT_SETREF (ac, res, res);
621                 MONO_OBJECT_SETREF (ac, msg->exc, exc);
622                 MONO_OBJECT_SETREF (ac, out_args, out_args);
623
624                 mono_monitor_enter ((MonoObject *) ares);
625                 ares->completed = 1;
626                 if (ares->handle != NULL)
627                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
628                 mono_monitor_exit ((MonoObject *) ares);
629                 /* notify listeners */
630                 if (wait_event != NULL)
631                         SetEvent (wait_event);
632
633                 /* call async callback if cb_method != null*/
634                 if (ac != NULL && ac->cb_method) {
635                         void *pa = &ares;
636                         cb_exc = NULL;
637                         mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
638                         exc = cb_exc;
639                 } else {
640                         exc = NULL;
641                 }
642         }
643
644         /* restore original thread execution context if flow isn't suppressed, i.e. non null */
645         if (ares->original_context) {
646                 mono_thread_set_execution_context (ares->original_context);
647                 ares->original_context = NULL;
648         }
649         return exc;
650 }
651
652 static void
653 threadpool_start_idle_threads (ThreadPool *tp)
654 {
655         int n;
656         guint32 stack_size;
657
658         stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
659         do {
660                 while (1) {
661                         n = tp->nthreads;
662                         if (n >= tp->min_threads)
663                                 return;
664                         if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
665                                 break;
666                 }
667 #ifndef DISABLE_PERFCOUNTERS
668                 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
669 #endif
670                 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
671                 SleepEx (100, TRUE);
672         } while (1);
673 }
674
675 static void
676 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
677 {
678         memset (tp, 0, sizeof (ThreadPool));
679         tp->min_threads = min_threads;
680         tp->max_threads = max_threads;
681         tp->async_invoke = async_invoke;
682         tp->queue = mono_cq_create ();
683         MONO_SEM_INIT (&tp->new_job, 0);
684 }
685
686 #ifndef DISABLE_PERFCOUNTERS
687 static void *
688 init_perf_counter (const char *category, const char *counter)
689 {
690         MonoString *category_str;
691         MonoString *counter_str;
692         MonoString *machine;
693         MonoDomain *root;
694         MonoBoolean custom;
695         int type;
696
697         if (category == NULL || counter == NULL)
698                 return NULL;
699         root = mono_get_root_domain ();
700         category_str = mono_string_new (root, category);
701         counter_str = mono_string_new (root, counter);
702         machine = mono_string_new (root, ".");
703         return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
704 }
705 #endif
706
707 #ifdef DEBUG
708 static void
709 print_pool_info (ThreadPool *tp)
710 {
711
712 //      if (tp->tail - tp->head == 0)
713 //              return;
714
715         g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
716         g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
717         g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
718         g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
719         g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
720         g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
721         g_print ("Queued: %d\n", (tp->tail - tp->head));
722         if (tp == &async_tp) {
723                 int i;
724                 EnterCriticalSection (&wsqs_lock);
725                 for (i = 0; i < wsqs->len; i++) {
726                         g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
727                 }
728                 LeaveCriticalSection (&wsqs_lock);
729         } else {
730                 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
731         }
732         g_print ("-------------\n");
733 }
734
735 static void
736 signal_handler (int signo)
737 {
738         ThreadPool *tp;
739
740         tp = &async_tp;
741         g_print ("\n-----Non-IO-----\n");
742         print_pool_info (tp);
743         tp = &async_io_tp;
744         g_print ("\n-----IO-----\n");
745         print_pool_info (tp);
746         alarm (2);
747 }
748 #endif
749
750 static void
751 monitor_thread (gpointer unused)
752 {
753         ThreadPool *pools [2];
754         MonoInternalThread *thread;
755         guint32 ms;
756         gboolean need_one;
757         int i;
758
759         pools [0] = &async_tp;
760         pools [1] = &async_io_tp;
761         thread = mono_thread_internal_current ();
762         ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threadpool monitor"));
763         while (1) {
764                 ms = 500;
765                 do {
766                         guint32 ts;
767                         ts = mono_msec_ticks ();
768                         if (SleepEx (ms, TRUE) == 0)
769                                 break;
770                         ms -= (mono_msec_ticks () - ts);
771                         if (mono_runtime_is_shutting_down ())
772                                 break;
773                         if (THREAD_WANTS_A_BREAK (thread))
774                                 mono_thread_interruption_checkpoint ();
775                 } while (ms > 0);
776
777                 if (mono_runtime_is_shutting_down ())
778                         break;
779
780                 for (i = 0; i < 2; i++) {
781                         ThreadPool *tp;
782                         tp = pools [i];
783                         if (tp->waiting > 0)
784                                 continue;
785                         need_one = (mono_cq_count (tp->queue) > 0);
786                         if (!need_one && !tp->is_io) {
787                                 EnterCriticalSection (&wsqs_lock);
788                                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
789                                         MonoWSQ *wsq;
790                                         wsq = g_ptr_array_index (wsqs, i);
791                                         if (mono_wsq_count (wsq) != 0) {
792                                                 need_one = TRUE;
793                                                 break;
794                                         }
795                                 }
796                                 LeaveCriticalSection (&wsqs_lock);
797                         }
798                         if (need_one)
799                                 threadpool_start_thread (tp);
800                 }
801         }
802 }
803
804 void
805 mono_thread_pool_init ()
806 {
807         gint threads_per_cpu = 1;
808         gint thread_count;
809         gint cpu_count = mono_cpu_count ();
810         int result;
811
812         if (tp_inited == 2)
813                 return;
814
815         result = InterlockedCompareExchange (&tp_inited, 1, 0);
816         if (result == 1) {
817                 while (1) {
818                         SleepEx (1, FALSE);
819                         if (tp_inited == 2)
820                                 return;
821                 }
822         }
823
824         MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
825         InitializeCriticalSection (&socket_io_data.io_lock);
826         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
827                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
828                 if (threads_per_cpu < 1)
829                         threads_per_cpu = 1;
830         }
831
832         thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
833         threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
834         threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
835         async_io_tp.is_io = TRUE;
836
837         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
838         g_assert (async_call_klass);
839
840         InitializeCriticalSection (&wsqs_lock);
841         wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
842         mono_wsq_init ();
843
844 #ifndef DISABLE_PERFCOUNTERS
845         async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
846         g_assert (async_tp.pc_nitems);
847
848         async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
849         g_assert (async_io_tp.pc_nitems);
850
851         async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
852         g_assert (async_tp.pc_nthreads);
853
854         async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
855         g_assert (async_io_tp.pc_nthreads);
856 #endif
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 #ifndef DISABLE_PERFCOUNTERS
1010                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1011 #endif
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                         threadpool_start_thread (tp);
1053                 }
1054                 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1055                  * the threadpool that much
1056                 * mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1057                 */
1058         }
1059
1060         for (i = 0; i < njobs; i++) {
1061                 ar = jobs [i];
1062                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1063                         continue; /* Might happen when cleaning domain jobs */
1064                 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1065                         MonoAsyncResult *o = (MonoAsyncResult *) ar;
1066                         o->add_time = mono_100ns_ticks ();
1067                 }
1068                 threadpool_jobs_inc (ar); 
1069 #ifndef DISABLE_PERFCOUNTERS
1070                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1071 #endif
1072                 if (!tp->is_io && mono_wsq_local_push (ar))
1073                         continue;
1074
1075                 mono_cq_enqueue (tp->queue, ar);
1076         }
1077
1078         for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1079                 pulse_on_new_job (tp);
1080 }
1081
1082 static void
1083 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1084 {
1085         MonoObject *obj;
1086         MonoMList *other;
1087
1088         other = NULL;
1089         while (mono_cq_dequeue (tp->queue, &obj)) {
1090                 if (obj == NULL)
1091                         continue;
1092                 if (obj->vtable->domain != domain)
1093                         other = mono_mlist_prepend (other, obj);
1094                 threadpool_jobs_dec (obj);
1095         }
1096
1097         while (other) {
1098                 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1099                 other = mono_mlist_next (other);
1100         }
1101 }
1102
1103 static gboolean
1104 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1105 {
1106         MonoMList *list = value;
1107         gboolean remove = FALSE;
1108         while (list) {
1109                 MonoObject *data = mono_mlist_get_data (list);
1110                 if (mono_object_domain (data) == user_data) {
1111                         remove = TRUE;
1112                         mono_mlist_set_data (list, NULL);
1113                 }
1114                 list = mono_mlist_next (list);
1115         }
1116         //FIXME is there some sort of additional unregistration we need to perform here?
1117         return remove;
1118 }
1119
1120 /*
1121  * Clean up the threadpool of all domain jobs.
1122  * Can only be called as part of the domain unloading process as
1123  * it will wait for all jobs to be visible to the interruption code. 
1124  */
1125 gboolean
1126 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1127 {
1128         HANDLE sem_handle;
1129         int result = TRUE;
1130         guint32 start_time = 0;
1131
1132         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1133
1134         threadpool_clear_queue (&async_tp, domain);
1135         threadpool_clear_queue (&async_io_tp, domain);
1136
1137         EnterCriticalSection (&socket_io_data.io_lock);
1138         if (socket_io_data.sock_to_state)
1139                 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1140
1141         LeaveCriticalSection (&socket_io_data.io_lock);
1142         
1143         /*
1144          * There might be some threads out that could be about to execute stuff from the given domain.
1145          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1146          */
1147         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1148
1149         domain->cleanup_semaphore = sem_handle;
1150         /*
1151          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1152          * and reading threadpool_jobs.
1153          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1154          */
1155         mono_memory_write_barrier ();
1156
1157         if (domain->threadpool_jobs && timeout != -1)
1158                 start_time = mono_msec_ticks ();
1159         while (domain->threadpool_jobs) {
1160                 WaitForSingleObject (sem_handle, timeout);
1161                 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1162                         result = FALSE;
1163                         break;
1164                 }
1165         }
1166
1167         domain->cleanup_semaphore = NULL;
1168         CloseHandle (sem_handle);
1169         return result;
1170 }
1171
1172 static void
1173 threadpool_free_queue (ThreadPool *tp)
1174 {
1175         mono_cq_destroy (tp->queue);
1176         tp->queue = NULL;
1177 }
1178
1179 gboolean
1180 mono_thread_pool_is_queue_array (MonoArray *o)
1181 {
1182         // gpointer obj = o;
1183
1184         // FIXME: need some fix in sgen code.
1185         return FALSE;
1186 }
1187
1188 static MonoWSQ *
1189 add_wsq (void)
1190 {
1191         int i;
1192         MonoWSQ *wsq;
1193
1194         EnterCriticalSection (&wsqs_lock);
1195         wsq = mono_wsq_create ();
1196         if (wsqs == NULL) {
1197                 LeaveCriticalSection (&wsqs_lock);
1198                 return NULL;
1199         }
1200         for (i = 0; i < wsqs->len; i++) {
1201                 if (g_ptr_array_index (wsqs, i) == NULL) {
1202                         wsqs->pdata [i] = wsq;
1203                         LeaveCriticalSection (&wsqs_lock);
1204                         return wsq;
1205                 }
1206         }
1207         g_ptr_array_add (wsqs, wsq);
1208         LeaveCriticalSection (&wsqs_lock);
1209         return wsq;
1210 }
1211
1212 static void
1213 remove_wsq (MonoWSQ *wsq)
1214 {
1215         gpointer data;
1216
1217         if (wsq == NULL)
1218                 return;
1219
1220         EnterCriticalSection (&wsqs_lock);
1221         if (wsqs == NULL) {
1222                 LeaveCriticalSection (&wsqs_lock);
1223                 return;
1224         }
1225         g_ptr_array_remove_fast (wsqs, wsq);
1226         data = NULL;
1227         /*
1228          * Only clean this up when shutting down, any other case will error out
1229          * if we're removing a queue that still has work items.
1230          */
1231         if (mono_runtime_is_shutting_down ()) {
1232                 while (mono_wsq_local_pop (&data)) {
1233                         threadpool_jobs_dec (data);
1234                         data = NULL;
1235                 }
1236         }
1237         mono_wsq_destroy (wsq);
1238         LeaveCriticalSection (&wsqs_lock);
1239 }
1240
1241 static void
1242 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1243 {
1244         int i;
1245         int ms;
1246
1247         if (wsqs == NULL || data == NULL || *data != NULL)
1248                 return;
1249
1250         ms = 0;
1251         do {
1252                 if (mono_runtime_is_shutting_down ())
1253                         return;
1254
1255                 EnterCriticalSection (&wsqs_lock);
1256                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1257                         MonoWSQ *wsq;
1258
1259                         wsq = wsqs->pdata [i];
1260                         if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1261                                 continue;
1262                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1263                         if (*data != NULL) {
1264                                 LeaveCriticalSection (&wsqs_lock);
1265                                 return;
1266                         }
1267                 }
1268                 LeaveCriticalSection (&wsqs_lock);
1269                 ms += 10;
1270         } while (retry && ms < 11);
1271 }
1272
1273 static gboolean
1274 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1275 {
1276         if (mono_runtime_is_shutting_down ())
1277                 return FALSE;
1278         mono_cq_dequeue (tp->queue, (MonoObject **) data);
1279         if (!tp->is_io && !*data)
1280                 try_steal (local_wsq, data, FALSE);
1281         return (*data != NULL);
1282 }
1283
1284 static void
1285 process_idle_times (ThreadPool *tp, gint64 t)
1286 {
1287         gint64 ticks;
1288         gint64 avg;
1289         gboolean compute_avg;
1290         gint new_threads;
1291         gint64 per1;
1292
1293         if (tp->ignore_times || t <= 0)
1294                 return;
1295
1296         compute_avg = FALSE;
1297         ticks = mono_100ns_ticks ();
1298         t = ticks - t;
1299         SPIN_LOCK (tp->sp_lock);
1300         if (tp->ignore_times) {
1301                 SPIN_UNLOCK (tp->sp_lock);
1302                 return;
1303         }
1304         tp->time_sum += t;
1305         tp->n_sum++;
1306         if (tp->last_check == 0)
1307                 tp->last_check = ticks;
1308         else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1309                 tp->ignore_times = 1;
1310                 compute_avg = TRUE;
1311         }
1312         SPIN_UNLOCK (tp->sp_lock);
1313
1314         if (!compute_avg)
1315                 return;
1316
1317         //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1318         tp->last_check = ticks;
1319         new_threads = 0;
1320         avg = tp->time_sum / tp->n_sum;
1321         if (tp->averages [1] == 0) {
1322                 tp->averages [1] = avg;
1323         } else {
1324                 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1325                 if (per1 > 5) {
1326                         if (avg > tp->averages [1]) {
1327                                 if (tp->averages [1] < tp->averages [0]) {
1328                                         new_threads = -1;
1329                                 } else {
1330                                         new_threads = 1;
1331                                 }
1332                         } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1333                                 new_threads = 1;
1334                         }
1335                 } else {
1336                         int min, n;
1337                         min = tp->min_threads;
1338                         n = tp->nthreads;
1339                         if ((n - min) < min && tp->busy_threads == n)
1340                                 new_threads = 1;
1341                 }
1342                 /*
1343                 if (new_threads != 0) {
1344                         printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1345                 }
1346                 */
1347         }
1348
1349         tp->time_sum = 0;
1350         tp->n_sum = 0;
1351
1352         tp->averages [0] = tp->averages [1];
1353         tp->averages [1] = avg;
1354         tp->ignore_times = 0;
1355
1356         if (new_threads == -1) {
1357                 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1358                         pulse_on_new_job (tp);
1359         }
1360 }
1361
1362 static gboolean
1363 should_i_die (ThreadPool *tp)
1364 {
1365         gboolean result = FALSE;
1366         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1367                 result = (tp->nthreads > tp->min_threads);
1368         return result;
1369 }
1370
1371 static void
1372 async_invoke_thread (gpointer data)
1373 {
1374         MonoDomain *domain;
1375         MonoInternalThread *thread;
1376         MonoWSQ *wsq;
1377         ThreadPool *tp;
1378         gboolean must_die;
1379         const gchar *name;
1380   
1381         tp = data;
1382         wsq = NULL;
1383         if (!tp->is_io)
1384                 wsq = add_wsq ();
1385
1386         thread = mono_thread_internal_current ();
1387
1388         mono_profiler_thread_start (thread->tid);
1389         name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1390         mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1391
1392         if (tp_start_func)
1393                 tp_start_func (tp_hooks_user_data);
1394
1395         data = NULL;
1396         for (;;) {
1397                 MonoAsyncResult *ar;
1398                 MonoClass *klass;
1399                 gboolean is_io_task;
1400                 gboolean is_socket;
1401                 int n_naps = 0;
1402
1403                 is_io_task = FALSE;
1404                 ar = (MonoAsyncResult *) data;
1405                 if (ar) {
1406                         InterlockedIncrement (&tp->busy_threads);
1407                         domain = ((MonoObject *)ar)->vtable->domain;
1408 #ifndef DISABLE_SOCKETS
1409                         klass = ((MonoObject *) data)->vtable->klass;
1410                         is_io_task = !is_corlib_asyncresult (domain, klass);
1411                         is_socket = FALSE;
1412                         if (is_io_task) {
1413                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1414                                 is_socket = is_socketasyncresult (domain, klass);
1415                                 ar = state->ares;
1416                                 switch (state->operation) {
1417                                 case AIO_OP_RECEIVE:
1418                                         state->total = ICALL_RECV (state);
1419                                         break;
1420                                 case AIO_OP_SEND:
1421                                         state->total = ICALL_SEND (state);
1422                                         break;
1423                                 }
1424                         }
1425 #endif
1426                         /* worker threads invokes methods in different domains,
1427                          * so we need to set the right domain here */
1428                         g_assert (domain);
1429
1430                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1431                                 threadpool_jobs_dec ((MonoObject *)ar);
1432                                 data = NULL;
1433                                 ar = NULL;
1434                                 InterlockedDecrement (&tp->busy_threads);
1435                         } else {
1436                                 mono_thread_push_appdomain_ref (domain);
1437                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1438                                         data = NULL;
1439                                         ar = NULL;
1440                                         mono_thread_pop_appdomain_ref ();
1441                                         InterlockedDecrement (&tp->busy_threads);
1442                                         continue;
1443                                 }
1444
1445                                 if (mono_domain_set (domain, FALSE)) {
1446                                         MonoObject *exc;
1447
1448                                         if (tp_item_begin_func)
1449                                                 tp_item_begin_func (tp_item_user_data);
1450
1451                                         if (!is_io_task && ar->add_time > 0)
1452                                                 process_idle_times (tp, ar->add_time);
1453                                         exc = mono_async_invoke (tp, ar);
1454                                         if (tp_item_end_func)
1455                                                 tp_item_end_func (tp_item_user_data);
1456                                         if (exc)
1457                                                 mono_internal_thread_unhandled_exception (exc);
1458                                         if (is_socket && tp->is_io) {
1459                                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1460
1461                                                 if (state->completed && state->callback) {
1462                                                         MonoAsyncResult *cb_ares;
1463                                                         cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1464                                                                                                 (MonoObject *) state);
1465                                                         icall_append_job ((MonoObject *) cb_ares);
1466                                                 }
1467                                         }
1468                                         mono_domain_set (mono_get_root_domain (), TRUE);
1469                                 }
1470                                 mono_thread_pop_appdomain_ref ();
1471                                 InterlockedDecrement (&tp->busy_threads);
1472                                 /* If the callee changes the background status, set it back to TRUE */
1473                                 mono_thread_clr_state (thread , ~ThreadState_Background);
1474                                 if (!mono_thread_test_state (thread , ThreadState_Background))
1475                                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1476                         }
1477                 }
1478
1479                 ar = NULL;
1480                 data = NULL;
1481                 must_die = should_i_die (tp);
1482                 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1483                         dequeue_or_steal (tp, &data, wsq);
1484
1485                 n_naps = 0;
1486                 while (!must_die && !data && n_naps < 4) {
1487                         gboolean res;
1488
1489                         InterlockedIncrement (&tp->waiting);
1490
1491                         // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1492                         // Check all the queues again before entering the wait loop
1493                         dequeue_or_steal (tp, &data, wsq);
1494                         if (data) {
1495                                 InterlockedDecrement (&tp->waiting);
1496                                 break;
1497                         }
1498
1499                         mono_gc_set_skip_thread (TRUE);
1500
1501 #if defined(__OpenBSD__)
1502                         while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1503 #else
1504                         while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1505 #endif
1506                                 if (mono_runtime_is_shutting_down ())
1507                                         break;
1508                                 if (THREAD_WANTS_A_BREAK (thread))
1509                                         mono_thread_interruption_checkpoint ();
1510                         }
1511                         InterlockedDecrement (&tp->waiting);
1512
1513                         mono_gc_set_skip_thread (FALSE);
1514
1515                         if (mono_runtime_is_shutting_down ())
1516                                 break;
1517                         must_die = should_i_die (tp);
1518                         dequeue_or_steal (tp, &data, wsq);
1519                         n_naps++;
1520                 }
1521
1522                 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1523                         mono_wsq_local_pop (&data);
1524                         if (data && must_die) {
1525                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1526                                 pulse_on_new_job (tp);
1527                         }
1528                 }
1529
1530                 if (!data) {
1531                         gint nt;
1532                         gboolean down;
1533                         while (1) {
1534                                 nt = tp->nthreads;
1535                                 down = mono_runtime_is_shutting_down ();
1536                                 if (!down && nt <= tp->min_threads)
1537                                         break;
1538                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1539 #ifndef DISABLE_PERFCOUNTERS
1540                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1541 #endif
1542                                         if (!tp->is_io) {
1543                                                 remove_wsq (wsq);
1544                                         }
1545
1546                                         mono_profiler_thread_end (thread->tid);
1547
1548                                         if (tp_finish_func)
1549                                                 tp_finish_func (tp_hooks_user_data);
1550                                         return;
1551                                 }
1552                         }
1553                 }
1554         }
1555
1556         g_assert_not_reached ();
1557 }
1558
1559 void
1560 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1561 {
1562         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1563         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1564 }
1565
1566 void
1567 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1568 {
1569         *workerThreads = async_tp.max_threads;
1570         *completionPortThreads = async_io_tp.max_threads;
1571 }
1572
1573 void
1574 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1575 {
1576         *workerThreads = async_tp.min_threads;
1577         *completionPortThreads = async_io_tp.min_threads;
1578 }
1579
1580 MonoBoolean
1581 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1582 {
1583         gint max_threads;
1584         gint max_io_threads;
1585
1586         max_threads = async_tp.max_threads;
1587         if (workerThreads <= 0 || workerThreads > max_threads)
1588                 return FALSE;
1589
1590         max_io_threads = async_io_tp.max_threads;
1591         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1592                 return FALSE;
1593
1594         InterlockedExchange (&async_tp.min_threads, workerThreads);
1595         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1596         if (workerThreads > async_tp.nthreads)
1597                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1598         if (completionPortThreads > async_io_tp.nthreads)
1599                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1600         return TRUE;
1601 }
1602
1603 MonoBoolean
1604 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1605 {
1606         gint min_threads;
1607         gint min_io_threads;
1608         gint cpu_count;
1609
1610         cpu_count = mono_cpu_count ();
1611         min_threads = async_tp.min_threads;
1612         if (workerThreads < min_threads || workerThreads < cpu_count)
1613                 return FALSE;
1614
1615         /* We don't really have the concept of completion ports. Do we care here? */
1616         min_io_threads = async_io_tp.min_threads;
1617         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1618                 return FALSE;
1619
1620         InterlockedExchange (&async_tp.max_threads, workerThreads);
1621         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1622         return TRUE;
1623 }
1624
1625 /**
1626  * mono_install_threadpool_thread_hooks
1627  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1628  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1629  * @user_data: argument passed to @start_func and @finish_func.
1630  *
1631  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1632  * The calls will be made from the thread itself.
1633  */
1634 void
1635 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1636 {
1637         tp_start_func = start_func;
1638         tp_finish_func = finish_func;
1639         tp_hooks_user_data = user_data;
1640 }
1641
1642 /**
1643  * mono_install_threadpool_item_hooks
1644  * @begin_func: the function to be called before a threadpool work item processing starts.
1645  * @end_func: the function to be called after a threadpool work item is finished.
1646  * @user_data: argument passed to @begin_func and @end_func.
1647  *
1648  * The calls will be made from the thread itself and from the same AppDomain
1649  * where the work item was executed.
1650  *
1651  */
1652 void
1653 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1654 {
1655         tp_item_begin_func = begin_func;
1656         tp_item_end_func = end_func;
1657         tp_item_user_data = user_data;
1658 }
1659
1660 void
1661 mono_internal_thread_unhandled_exception (MonoObject* exc)
1662 {
1663         if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1664                 gboolean unloaded;
1665                 MonoClass *klass;
1666
1667                 klass = exc->vtable->klass;
1668                 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1669                 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1670                         mono_unhandled_exception (exc);
1671                         if (mono_environment_exitcode_get () == 1)
1672                                 exit (255);
1673                 }
1674                 if (klass == mono_defaults.threadabortexception_class)
1675                  mono_thread_internal_reset_abort (mono_thread_internal_current ());
1676         }
1677 }