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