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