Merge pull request #1696 from esdrubal/tzrefactor
[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_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1007                       MonoObject *state)
1008 {
1009         MonoDomain *domain;
1010         MonoAsyncResult *ares;
1011         MonoAsyncCall *ac;
1012
1013         if (use_ms_threadpool ())
1014                 return mono_threadpool_ms_add (target, msg, async_callback, state);
1015
1016         domain = mono_domain_get ();
1017
1018         ac = (MonoAsyncCall*)mono_object_new (domain, async_call_klass);
1019         MONO_OBJECT_SETREF (ac, msg, msg);
1020         MONO_OBJECT_SETREF (ac, state, state);
1021
1022         if (async_callback) {
1023                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1024                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1025         }
1026
1027         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1028         MONO_OBJECT_SETREF (ares, async_delegate, target);
1029
1030 #ifndef DISABLE_SOCKETS
1031         if (socket_io_filter (target, state)) {
1032                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1033                 return ares;
1034         }
1035 #endif
1036         threadpool_append_job (&async_tp, (MonoObject *) ares);
1037         return ares;
1038 }
1039
1040 MonoObject *
1041 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1042 {
1043         MonoAsyncCall *ac;
1044         HANDLE wait_event;
1045
1046         if (use_ms_threadpool ()) {
1047                 return mono_threadpool_ms_finish (ares, out_args, exc);
1048         }
1049
1050         *exc = NULL;
1051         *out_args = NULL;
1052
1053         /* check if already finished */
1054         mono_monitor_enter ((MonoObject *) ares);
1055         
1056         if (ares->endinvoke_called) {
1057                 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1058                 mono_monitor_exit ((MonoObject *) ares);
1059                 return NULL;
1060         }
1061
1062         ares->endinvoke_called = 1;
1063         /* wait until we are really finished */
1064         if (!ares->completed) {
1065                 if (ares->handle == NULL) {
1066                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1067                         g_assert(wait_event != 0);
1068                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1069                 } else {
1070                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1071                 }
1072                 mono_monitor_exit ((MonoObject *) ares);
1073                 MONO_PREPARE_BLOCKING
1074                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1075                 MONO_FINISH_BLOCKING
1076         } else {
1077                 mono_monitor_exit ((MonoObject *) ares);
1078         }
1079
1080         ac = (MonoAsyncCall *) ares->object_data;
1081         g_assert (ac != NULL);
1082         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1083         *out_args = ac->out_args;
1084
1085         return ac->res;
1086 }
1087
1088 static void
1089 threadpool_kill_idle_threads (ThreadPool *tp)
1090 {
1091         gint n;
1092
1093         n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1094         while (n) {
1095                 n--;
1096                 MONO_SEM_POST (&tp->new_job);
1097         }
1098 }
1099
1100 void
1101 mono_thread_pool_cleanup (void)
1102 {
1103         if (use_ms_threadpool ()) {
1104                 mono_threadpool_ms_cleanup ();
1105                 return;
1106         }
1107
1108         if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
1109                 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1110                 threadpool_kill_idle_threads (&async_io_tp);
1111         }
1112
1113         if (async_io_tp.queue != NULL) {
1114                 MONO_SEM_DESTROY (&async_io_tp.new_job);
1115                 threadpool_free_queue (&async_io_tp);
1116         }
1117
1118
1119         if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1120                 threadpool_kill_idle_threads (&async_tp);
1121                 threadpool_free_queue (&async_tp);
1122         }
1123         
1124         if (threads) {
1125                 mono_mutex_lock (&threads_lock);
1126                 if (threads)
1127                         g_ptr_array_free (threads, FALSE);
1128                 threads = NULL;
1129                 mono_mutex_unlock (&threads_lock);
1130         }
1131
1132         if (wsqs) {
1133                 mono_mutex_lock (&wsqs_lock);
1134                 mono_wsq_cleanup ();
1135                 if (wsqs)
1136                         g_ptr_array_free (wsqs, TRUE);
1137                 wsqs = NULL;
1138                 mono_mutex_unlock (&wsqs_lock);
1139                 MONO_SEM_DESTROY (&async_tp.new_job);
1140         }
1141
1142         MONO_SEM_DESTROY (&monitor_sem);
1143 }
1144
1145 static gboolean
1146 threadpool_start_thread (ThreadPool *tp)
1147 {
1148         gint n;
1149         guint32 stack_size;
1150         MonoInternalThread *thread;
1151
1152         stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1153         while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1154                 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1155 #ifndef DISABLE_PERFCOUNTERS
1156                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1157 #endif
1158                         if (tp->is_io) {
1159                                 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1160                         } else {
1161                                 mono_mutex_lock (&threads_lock);
1162                                 thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
1163                                 g_assert (threads != NULL);
1164                                 g_ptr_array_add (threads, thread);
1165                                 mono_mutex_unlock (&threads_lock);
1166                         }
1167                         return TRUE;
1168                 }
1169         }
1170
1171         return FALSE;
1172 }
1173
1174 static void
1175 pulse_on_new_job (ThreadPool *tp)
1176 {
1177         if (tp->waiting)
1178                 MONO_SEM_POST (&tp->new_job);
1179 }
1180
1181 static void
1182 threadpool_kill_thread (ThreadPool *tp)
1183 {
1184         if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1185                 pulse_on_new_job (tp);
1186 }
1187
1188 void
1189 icall_append_job (MonoObject *ar)
1190 {
1191         threadpool_append_jobs (&async_tp, &ar, 1);
1192 }
1193
1194 static void
1195 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1196 {
1197         threadpool_append_jobs (tp, &ar, 1);
1198 }
1199
1200 void
1201 threadpool_append_async_io_jobs (MonoObject **jobs, gint njobs)
1202 {
1203         threadpool_append_jobs (&async_io_tp, jobs, njobs);
1204 }
1205
1206 static void
1207 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1208 {
1209         MonoObject *ar;
1210         gint i;
1211
1212         if (mono_runtime_is_shutting_down ())
1213                 return;
1214
1215         if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1216                 if (!tp->is_io) {
1217                         monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
1218                         monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
1219                         threadpool_start_thread (tp);
1220                 }
1221                 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1222                  * the threadpool that much
1223                  */
1224                 if (mono_config_is_server_mode ()) {
1225                         mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, SMALL_STACK);
1226                 }
1227         }
1228
1229         InterlockedAdd (&monitor_njobs, njobs);
1230
1231         if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
1232                 MONO_SEM_POST (&monitor_sem);
1233
1234         if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
1235                 InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
1236
1237         for (i = 0; i < njobs; i++) {
1238                 ar = jobs [i];
1239                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1240                         continue; /* Might happen when cleaning domain jobs */
1241                 threadpool_jobs_inc (ar); 
1242 #ifndef DISABLE_PERFCOUNTERS
1243                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1244 #endif
1245                 if (!tp->is_io && mono_wsq_local_push (ar))
1246                         continue;
1247
1248                 mono_cq_enqueue (tp->queue, ar);
1249         }
1250
1251 #if DEBUG
1252         InterlockedAdd (&tp->njobs, njobs);
1253 #endif
1254
1255         for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1256                 pulse_on_new_job (tp);
1257 }
1258
1259 static void
1260 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1261 {
1262         MonoObject *obj;
1263         MonoMList *other = NULL;
1264         MonoCQ *queue = tp->queue;
1265
1266         if (!queue)
1267                 return;
1268
1269         while (mono_cq_dequeue (queue, &obj)) {
1270                 if (obj == NULL)
1271                         continue;
1272                 if (obj->vtable->domain != domain)
1273                         other = mono_mlist_prepend (other, obj);
1274                 threadpool_jobs_dec (obj);
1275         }
1276
1277         if (mono_runtime_is_shutting_down ())
1278                 return;
1279
1280         while (other) {
1281                 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1282                 other = mono_mlist_next (other);
1283         }
1284 }
1285
1286 static gboolean
1287 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1288 {
1289         MonoMList *list = value;
1290         gboolean remove = FALSE;
1291         while (list) {
1292                 MonoObject *data = mono_mlist_get_data (list);
1293                 if (mono_object_domain (data) == user_data) {
1294                         remove = TRUE;
1295                         mono_mlist_set_data (list, NULL);
1296                 }
1297                 list = mono_mlist_next (list);
1298         }
1299         //FIXME is there some sort of additional unregistration we need to perform here?
1300         return remove;
1301 }
1302
1303 /*
1304  * Clean up the threadpool of all domain jobs.
1305  * Can only be called as part of the domain unloading process as
1306  * it will wait for all jobs to be visible to the interruption code. 
1307  */
1308 gboolean
1309 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1310 {
1311         HANDLE sem_handle;
1312         int result;
1313         guint32 start_time;
1314
1315         if (use_ms_threadpool ()) {
1316                 return mono_threadpool_ms_remove_domain_jobs (domain, timeout);
1317         }
1318
1319         result = TRUE;
1320         start_time = 0;
1321
1322         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1323
1324         threadpool_clear_queue (&async_tp, domain);
1325         threadpool_clear_queue (&async_io_tp, domain);
1326
1327         mono_mutex_lock (&socket_io_data.io_lock);
1328         if (socket_io_data.sock_to_state)
1329                 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1330
1331         mono_mutex_unlock (&socket_io_data.io_lock);
1332         
1333         /*
1334          * There might be some threads out that could be about to execute stuff from the given domain.
1335          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1336          */
1337         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1338
1339         domain->cleanup_semaphore = sem_handle;
1340         /*
1341          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1342          * and reading threadpool_jobs.
1343          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1344          */
1345         mono_memory_write_barrier ();
1346
1347         if (domain->threadpool_jobs && timeout != -1)
1348                 start_time = mono_msec_ticks ();
1349         while (domain->threadpool_jobs) {
1350                 MONO_PREPARE_BLOCKING
1351                 WaitForSingleObject (sem_handle, timeout);
1352                 MONO_FINISH_BLOCKING
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_PREPARE_BLOCKING
1452                 mono_mutex_lock (&wsqs_lock);
1453                 MONO_FINISH_BLOCKING
1454                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1455                         MonoWSQ *wsq;
1456
1457                         wsq = wsqs->pdata [i];
1458                         if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1459                                 continue;
1460                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1461                         if (*data != NULL) {
1462                                 mono_mutex_unlock (&wsqs_lock);
1463                                 return;
1464                         }
1465                 }
1466                 mono_mutex_unlock (&wsqs_lock);
1467                 ms += 10;
1468         } while (retry && ms < 11);
1469 }
1470
1471 static gboolean
1472 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1473 {
1474         MonoCQ *queue = tp->queue;
1475         if (mono_runtime_is_shutting_down () || !queue)
1476                 return FALSE;
1477         mono_cq_dequeue (queue, (MonoObject **) data);
1478         if (!tp->is_io && !*data)
1479                 try_steal (local_wsq, data, FALSE);
1480         return (*data != NULL);
1481 }
1482
1483 static gboolean
1484 should_i_die (ThreadPool *tp)
1485 {
1486         gboolean result = FALSE;
1487         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1488                 result = (tp->nthreads > tp->min_threads);
1489         return result;
1490 }
1491
1492 static void
1493 set_tp_thread_info (ThreadPool *tp)
1494 {
1495         const gchar *name;
1496         MonoInternalThread *thread = mono_thread_internal_current ();
1497
1498         mono_profiler_thread_start (thread->tid);
1499         name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1500         mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1501 }
1502
1503 static void
1504 clear_thread_state (void)
1505 {
1506         MonoInternalThread *thread = mono_thread_internal_current ();
1507         /* If the callee changes the background status, set it back to TRUE */
1508         mono_thread_clr_state (thread , ~ThreadState_Background);
1509         if (!mono_thread_test_state (thread , ThreadState_Background))
1510                 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1511 }
1512
1513 void
1514 check_for_interruption_critical (void)
1515 {
1516         MonoInternalThread *thread;
1517         /*RULE NUMBER ONE OF SKIP_THREAD: NEVER POKE MANAGED STATE.*/
1518         mono_gc_set_skip_thread (FALSE);
1519
1520         thread = mono_thread_internal_current ();
1521         if (THREAD_WANTS_A_BREAK (thread))
1522                 mono_thread_interruption_checkpoint ();
1523
1524         /*RULE NUMBER TWO OF SKIP_THREAD: READ RULE NUMBER ONE.*/
1525         mono_gc_set_skip_thread (TRUE);
1526 }
1527
1528 static void
1529 fire_profiler_thread_end (void)
1530 {
1531         MonoInternalThread *thread = mono_thread_internal_current ();
1532         mono_profiler_thread_end (thread->tid);
1533 }
1534
1535 static void
1536 async_invoke_thread (gpointer data)
1537 {
1538         MonoDomain *domain;
1539         MonoWSQ *wsq;
1540         ThreadPool *tp;
1541         gboolean must_die;
1542   
1543         tp = data;
1544         wsq = NULL;
1545         if (!tp->is_io)
1546                 wsq = add_wsq ();
1547
1548         set_tp_thread_info (tp);
1549
1550         if (tp_start_func)
1551                 tp_start_func (tp_hooks_user_data);
1552
1553         data = NULL;
1554         for (;;) {
1555                 MonoAsyncResult *ar;
1556                 MonoClass *klass;
1557                 gboolean is_io_task;
1558                 gboolean is_socket;
1559                 int n_naps = 0;
1560
1561                 is_io_task = FALSE;
1562                 ar = (MonoAsyncResult *) data;
1563                 if (ar) {
1564                         InterlockedIncrement (&tp->busy_threads);
1565                         domain = ((MonoObject *)ar)->vtable->domain;
1566 #ifndef DISABLE_SOCKETS
1567                         klass = ((MonoObject *) data)->vtable->klass;
1568                         is_io_task = !is_corlib_asyncresult (domain, klass);
1569                         is_socket = FALSE;
1570                         if (is_io_task) {
1571                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1572                                 is_socket = is_socketasyncresult (domain, klass);
1573                                 ar = state->ares;
1574                         }
1575 #endif
1576                         /* worker threads invokes methods in different domains,
1577                          * so we need to set the right domain here */
1578                         g_assert (domain);
1579
1580                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1581                                 threadpool_jobs_dec ((MonoObject *)ar);
1582                                 data = NULL;
1583                                 ar = NULL;
1584                                 InterlockedDecrement (&tp->busy_threads);
1585                         } else {
1586                                 mono_thread_push_appdomain_ref (domain);
1587                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1588                                         data = NULL;
1589                                         ar = NULL;
1590                                         mono_thread_pop_appdomain_ref ();
1591                                         InterlockedDecrement (&tp->busy_threads);
1592                                         continue;
1593                                 }
1594
1595                                 if (mono_domain_set (domain, FALSE)) {
1596                                         MonoObject *exc;
1597
1598                                         if (tp_item_begin_func)
1599                                                 tp_item_begin_func (tp_item_user_data);
1600
1601                                         exc = mono_async_invoke (tp, ar);
1602                                         if (tp_item_end_func)
1603                                                 tp_item_end_func (tp_item_user_data);
1604                                         if (exc)
1605                                                 mono_internal_thread_unhandled_exception (exc);
1606                                         if (is_socket && tp->is_io) {
1607                                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1608
1609                                                 if (state->completed && state->callback) {
1610                                                         MonoAsyncResult *cb_ares;
1611                                                         cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1612                                                                                                 (MonoObject *) state);
1613                                                         icall_append_job ((MonoObject *) cb_ares);
1614                                                 }
1615                                         }
1616                                         mono_domain_set (mono_get_root_domain (), TRUE);
1617                                 }
1618                                 mono_thread_pop_appdomain_ref ();
1619                                 InterlockedDecrement (&tp->busy_threads);
1620                                 clear_thread_state ();
1621                         }
1622                 }
1623
1624                 ar = NULL;
1625                 data = NULL;
1626                 must_die = should_i_die (tp);
1627                 if (must_die) {
1628                         mono_wsq_suspend (wsq);
1629                 } else {
1630                         if (tp->is_io || !mono_wsq_local_pop (&data))
1631                                 dequeue_or_steal (tp, &data, wsq);
1632                 }
1633
1634                 n_naps = 0;
1635                 while (!must_die && !data && n_naps < 4) {
1636                         gboolean res;
1637
1638                         InterlockedIncrement (&tp->waiting);
1639
1640                         // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1641                         // Check all the queues again before entering the wait loop
1642                         dequeue_or_steal (tp, &data, wsq);
1643                         if (data) {
1644                                 InterlockedDecrement (&tp->waiting);
1645                                 break;
1646                         }
1647
1648                         mono_gc_set_skip_thread (TRUE);
1649                         MONO_PREPARE_BLOCKING
1650
1651 #if defined(__OpenBSD__)
1652                         while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1653 #else
1654                         while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1655 #endif
1656                                 if (mono_runtime_is_shutting_down ())
1657                                         break;
1658                                 check_for_interruption_critical ();
1659                         }
1660                         InterlockedDecrement (&tp->waiting);
1661
1662                         MONO_FINISH_BLOCKING
1663                         mono_gc_set_skip_thread (FALSE);
1664
1665                         if (mono_runtime_is_shutting_down ())
1666                                 break;
1667                         must_die = should_i_die (tp);
1668                         dequeue_or_steal (tp, &data, wsq);
1669                         n_naps++;
1670                 }
1671
1672                 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1673                         mono_wsq_local_pop (&data);
1674                         if (data && must_die) {
1675                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1676                                 pulse_on_new_job (tp);
1677                         }
1678                 }
1679
1680                 if (!data) {
1681                         gint nt;
1682                         gboolean down;
1683                         while (1) {
1684                                 nt = tp->nthreads;
1685                                 down = mono_runtime_is_shutting_down ();
1686                                 if (!down && nt <= tp->min_threads)
1687                                         break;
1688                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1689 #ifndef DISABLE_PERFCOUNTERS
1690                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1691 #endif
1692                                         if (!tp->is_io) {
1693                                                 remove_wsq (wsq);
1694                                         }
1695
1696                                         fire_profiler_thread_end ();
1697
1698                                         if (tp_finish_func)
1699                                                 tp_finish_func (tp_hooks_user_data);
1700
1701                                         if (!tp->is_io) {
1702                                                 if (threads) {
1703                                                         mono_mutex_lock (&threads_lock);
1704                                                         if (threads)
1705                                                                 g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
1706                                                         mono_mutex_unlock (&threads_lock);
1707                                                 }
1708                                         }
1709
1710                                         return;
1711                                 }
1712                         }
1713                 }
1714         }
1715
1716         g_assert_not_reached ();
1717 }
1718
1719 void
1720 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1721 {
1722         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1723         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1724 }
1725
1726 void
1727 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1728 {
1729         *workerThreads = async_tp.max_threads;
1730         *completionPortThreads = async_io_tp.max_threads;
1731 }
1732
1733 void
1734 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1735 {
1736         *workerThreads = async_tp.min_threads;
1737         *completionPortThreads = async_io_tp.min_threads;
1738 }
1739
1740 MonoBoolean
1741 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1742 {
1743         gint max_threads;
1744         gint max_io_threads;
1745
1746         max_threads = async_tp.max_threads;
1747         if (workerThreads <= 0 || workerThreads > max_threads)
1748                 return FALSE;
1749
1750         max_io_threads = async_io_tp.max_threads;
1751         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1752                 return FALSE;
1753
1754         InterlockedExchange (&async_tp.min_threads, workerThreads);
1755         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1756         if (workerThreads > async_tp.nthreads)
1757                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, SMALL_STACK);
1758         if (completionPortThreads > async_io_tp.nthreads)
1759                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, SMALL_STACK);
1760         return TRUE;
1761 }
1762
1763 MonoBoolean
1764 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1765 {
1766         gint min_threads;
1767         gint min_io_threads;
1768         gint cpu_count;
1769
1770         cpu_count = mono_cpu_count ();
1771         min_threads = async_tp.min_threads;
1772         if (workerThreads < min_threads || workerThreads < cpu_count)
1773                 return FALSE;
1774
1775         /* We don't really have the concept of completion ports. Do we care here? */
1776         min_io_threads = async_io_tp.min_threads;
1777         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1778                 return FALSE;
1779
1780         InterlockedExchange (&async_tp.max_threads, workerThreads);
1781         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1782         return TRUE;
1783 }
1784
1785 /**
1786  * mono_install_threadpool_thread_hooks
1787  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1788  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1789  * @user_data: argument passed to @start_func and @finish_func.
1790  *
1791  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1792  * The calls will be made from the thread itself.
1793  */
1794 void
1795 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1796 {
1797         tp_start_func = start_func;
1798         tp_finish_func = finish_func;
1799         tp_hooks_user_data = user_data;
1800 }
1801
1802 /**
1803  * mono_install_threadpool_item_hooks
1804  * @begin_func: the function to be called before a threadpool work item processing starts.
1805  * @end_func: the function to be called after a threadpool work item is finished.
1806  * @user_data: argument passed to @begin_func and @end_func.
1807  *
1808  * The calls will be made from the thread itself and from the same AppDomain
1809  * where the work item was executed.
1810  *
1811  */
1812 void
1813 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1814 {
1815         tp_item_begin_func = begin_func;
1816         tp_item_end_func = end_func;
1817         tp_item_user_data = user_data;
1818 }
1819
1820 void
1821 mono_internal_thread_unhandled_exception (MonoObject* exc)
1822 {
1823         if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1824                 gboolean unloaded;
1825                 MonoClass *klass;
1826
1827                 klass = exc->vtable->klass;
1828                 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1829                 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1830                         mono_unhandled_exception (exc);
1831                         if (mono_environment_exitcode_get () == 1)
1832                                 exit (255);
1833                 }
1834                 if (klass == mono_defaults.threadabortexception_class)
1835                  mono_thread_internal_reset_abort (mono_thread_internal_current ());
1836         }
1837 }
1838
1839 /*
1840  * Suspend creation of new threads.
1841  */
1842 void
1843 mono_thread_pool_suspend (void)
1844 {
1845         if (use_ms_threadpool ()) {
1846                 mono_threadpool_ms_suspend ();
1847                 return;
1848         }
1849         suspended = TRUE;
1850 }
1851
1852 /*
1853  * Resume creation of new threads.
1854  */
1855 void
1856 mono_thread_pool_resume (void)
1857 {
1858         if (use_ms_threadpool ()) {
1859                 mono_threadpool_ms_resume ();
1860                 return;
1861         }
1862         suspended = FALSE;
1863 }