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