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