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