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