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