Merge pull request #642 from Ventero/CleanCopyLocal
[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_tls (void)
818 {
819         mono_wsq_init ();
820 }
821
822 void
823 mono_thread_pool_init (void)
824 {
825         gint threads_per_cpu = 1;
826         gint thread_count;
827         gint cpu_count = mono_cpu_count ();
828         int result;
829
830         if (tp_inited == 2)
831                 return;
832
833         result = InterlockedCompareExchange (&tp_inited, 1, 0);
834         if (result == 1) {
835                 while (1) {
836                         SleepEx (1, FALSE);
837                         if (tp_inited == 2)
838                                 return;
839                 }
840         }
841
842         MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
843         InitializeCriticalSection (&socket_io_data.io_lock);
844         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
845                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
846                 if (threads_per_cpu < 1)
847                         threads_per_cpu = 1;
848         }
849
850         thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
851         threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
852         threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
853         async_io_tp.is_io = TRUE;
854
855         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
856         g_assert (async_call_klass);
857
858         InitializeCriticalSection (&wsqs_lock);
859         wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
860
861 #ifndef DISABLE_PERFCOUNTERS
862         async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
863         g_assert (async_tp.pc_nitems);
864
865         async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
866         g_assert (async_io_tp.pc_nitems);
867
868         async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
869         g_assert (async_tp.pc_nthreads);
870
871         async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
872         g_assert (async_io_tp.pc_nthreads);
873 #endif
874         tp_inited = 2;
875 #ifdef DEBUG
876         signal (SIGALRM, signal_handler);
877         alarm (2);
878 #endif
879 }
880
881 static MonoAsyncResult *
882 create_simple_asyncresult (MonoObject *target, MonoObject *state)
883 {
884         MonoDomain *domain = mono_domain_get ();
885         MonoAsyncResult *ares;
886
887         /* Don't call mono_async_result_new() to avoid capturing the context */
888         ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
889         MONO_OBJECT_SETREF (ares, async_delegate, target);
890         MONO_OBJECT_SETREF (ares, async_state, state);
891         return ares;
892 }
893
894 void
895 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
896 {
897         MonoAsyncResult *ares;
898
899         ares = create_simple_asyncresult (target, (MonoObject *) state);
900         socket_io_add (ares, state);
901 }
902
903 MonoAsyncResult *
904 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
905                       MonoObject *state)
906 {
907         MonoDomain *domain = mono_domain_get ();
908         MonoAsyncResult *ares;
909         ASyncCall *ac;
910
911         ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
912         MONO_OBJECT_SETREF (ac, msg, msg);
913         MONO_OBJECT_SETREF (ac, state, state);
914
915         if (async_callback) {
916                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
917                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
918         }
919
920         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
921         MONO_OBJECT_SETREF (ares, async_delegate, target);
922
923 #ifndef DISABLE_SOCKETS
924         if (socket_io_filter (target, state)) {
925                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
926                 return ares;
927         }
928 #endif
929         threadpool_append_job (&async_tp, (MonoObject *) ares);
930         return ares;
931 }
932
933 MonoObject *
934 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
935 {
936         ASyncCall *ac;
937         HANDLE wait_event;
938
939         *exc = NULL;
940         *out_args = NULL;
941
942         /* check if already finished */
943         mono_monitor_enter ((MonoObject *) ares);
944         
945         if (ares->endinvoke_called) {
946                 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
947                 mono_monitor_exit ((MonoObject *) ares);
948                 return NULL;
949         }
950
951         ares->endinvoke_called = 1;
952         /* wait until we are really finished */
953         if (!ares->completed) {
954                 if (ares->handle == NULL) {
955                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
956                         g_assert(wait_event != 0);
957                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
958                 } else {
959                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
960                 }
961                 mono_monitor_exit ((MonoObject *) ares);
962                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
963         } else {
964                 mono_monitor_exit ((MonoObject *) ares);
965         }
966
967         ac = (ASyncCall *) ares->object_data;
968         g_assert (ac != NULL);
969         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
970         *out_args = ac->out_args;
971
972         return ac->res;
973 }
974
975 static void
976 threadpool_kill_idle_threads (ThreadPool *tp)
977 {
978         gint n;
979
980         n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
981         while (n) {
982                 n--;
983                 MONO_SEM_POST (&tp->new_job);
984         }
985 }
986
987 void
988 mono_thread_pool_cleanup (void)
989 {
990         if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
991                 socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
992                 threadpool_kill_idle_threads (&async_io_tp);
993         }
994
995         if (async_io_tp.queue != NULL) {
996                 MONO_SEM_DESTROY (&async_io_tp.new_job);
997                 threadpool_free_queue (&async_io_tp);
998         }
999
1000
1001         if (InterlockedExchange (&async_tp.pool_status, 2) == 1) {
1002                 threadpool_kill_idle_threads (&async_tp);
1003                 threadpool_free_queue (&async_tp);
1004         }
1005
1006         if (wsqs) {
1007                 EnterCriticalSection (&wsqs_lock);
1008                 mono_wsq_cleanup ();
1009                 if (wsqs)
1010                         g_ptr_array_free (wsqs, TRUE);
1011                 wsqs = NULL;
1012                 LeaveCriticalSection (&wsqs_lock);
1013                 MONO_SEM_DESTROY (&async_tp.new_job);
1014         }
1015 }
1016
1017 static gboolean
1018 threadpool_start_thread (ThreadPool *tp)
1019 {
1020         gint n;
1021         guint32 stack_size;
1022
1023         stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
1024         while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1025                 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1026 #ifndef DISABLE_PERFCOUNTERS
1027                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1028 #endif
1029                         mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, FALSE, stack_size);
1030                         return TRUE;
1031                 }
1032         }
1033
1034         return FALSE;
1035 }
1036
1037 static void
1038 pulse_on_new_job (ThreadPool *tp)
1039 {
1040         if (tp->waiting)
1041                 MONO_SEM_POST (&tp->new_job);
1042 }
1043
1044 void
1045 icall_append_job (MonoObject *ar)
1046 {
1047         threadpool_append_jobs (&async_tp, &ar, 1);
1048 }
1049
1050 static void
1051 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1052 {
1053         threadpool_append_jobs (tp, &ar, 1);
1054 }
1055
1056 static void
1057 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1058 {
1059         static int job_counter;
1060         MonoObject *ar;
1061         gint i;
1062
1063         if (mono_runtime_is_shutting_down ())
1064                 return;
1065
1066         if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
1067                 if (!tp->is_io) {
1068                         mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, FALSE, SMALL_STACK);
1069                         threadpool_start_thread (tp);
1070                 }
1071                 /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
1072                  * the threadpool that much
1073                 * mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE, FALSE, SMALL_STACK);
1074                 */
1075         }
1076
1077         for (i = 0; i < njobs; i++) {
1078                 ar = jobs [i];
1079                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1080                         continue; /* Might happen when cleaning domain jobs */
1081                 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1082                         MonoAsyncResult *o = (MonoAsyncResult *) ar;
1083                         o->add_time = mono_100ns_ticks ();
1084                 }
1085                 threadpool_jobs_inc (ar); 
1086 #ifndef DISABLE_PERFCOUNTERS
1087                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1088 #endif
1089                 if (!tp->is_io && mono_wsq_local_push (ar))
1090                         continue;
1091
1092                 mono_cq_enqueue (tp->queue, ar);
1093         }
1094
1095         for (i = 0; tp->waiting > 0 && i < MIN(njobs, tp->max_threads); i++)
1096                 pulse_on_new_job (tp);
1097 }
1098
1099 static void
1100 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1101 {
1102         MonoObject *obj;
1103         MonoMList *other = NULL;
1104         MonoCQ *queue = tp->queue;
1105
1106         if (!queue)
1107                 return;
1108
1109         while (mono_cq_dequeue (queue, &obj)) {
1110                 if (obj == NULL)
1111                         continue;
1112                 if (obj->vtable->domain != domain)
1113                         other = mono_mlist_prepend (other, obj);
1114                 threadpool_jobs_dec (obj);
1115         }
1116
1117         if (mono_runtime_is_shutting_down ())
1118                 return;
1119
1120         while (other) {
1121                 threadpool_append_job (tp, (MonoObject *) mono_mlist_get_data (other));
1122                 other = mono_mlist_next (other);
1123         }
1124 }
1125
1126 static gboolean
1127 remove_sockstate_for_domain (gpointer key, gpointer value, gpointer user_data)
1128 {
1129         MonoMList *list = value;
1130         gboolean remove = FALSE;
1131         while (list) {
1132                 MonoObject *data = mono_mlist_get_data (list);
1133                 if (mono_object_domain (data) == user_data) {
1134                         remove = TRUE;
1135                         mono_mlist_set_data (list, NULL);
1136                 }
1137                 list = mono_mlist_next (list);
1138         }
1139         //FIXME is there some sort of additional unregistration we need to perform here?
1140         return remove;
1141 }
1142
1143 /*
1144  * Clean up the threadpool of all domain jobs.
1145  * Can only be called as part of the domain unloading process as
1146  * it will wait for all jobs to be visible to the interruption code. 
1147  */
1148 gboolean
1149 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1150 {
1151         HANDLE sem_handle;
1152         int result = TRUE;
1153         guint32 start_time = 0;
1154
1155         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1156
1157         threadpool_clear_queue (&async_tp, domain);
1158         threadpool_clear_queue (&async_io_tp, domain);
1159
1160         EnterCriticalSection (&socket_io_data.io_lock);
1161         if (socket_io_data.sock_to_state)
1162                 mono_g_hash_table_foreach_remove (socket_io_data.sock_to_state, remove_sockstate_for_domain, domain);
1163
1164         LeaveCriticalSection (&socket_io_data.io_lock);
1165         
1166         /*
1167          * There might be some threads out that could be about to execute stuff from the given domain.
1168          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1169          */
1170         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1171
1172         domain->cleanup_semaphore = sem_handle;
1173         /*
1174          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1175          * and reading threadpool_jobs.
1176          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1177          */
1178         mono_memory_write_barrier ();
1179
1180         if (domain->threadpool_jobs && timeout != -1)
1181                 start_time = mono_msec_ticks ();
1182         while (domain->threadpool_jobs) {
1183                 WaitForSingleObject (sem_handle, timeout);
1184                 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1185                         result = FALSE;
1186                         break;
1187                 }
1188         }
1189
1190         domain->cleanup_semaphore = NULL;
1191         CloseHandle (sem_handle);
1192         return result;
1193 }
1194
1195 static void
1196 threadpool_free_queue (ThreadPool *tp)
1197 {
1198         mono_cq_destroy (tp->queue);
1199         tp->queue = NULL;
1200 }
1201
1202 gboolean
1203 mono_thread_pool_is_queue_array (MonoArray *o)
1204 {
1205         // gpointer obj = o;
1206
1207         // FIXME: need some fix in sgen code.
1208         return FALSE;
1209 }
1210
1211 static MonoWSQ *
1212 add_wsq (void)
1213 {
1214         int i;
1215         MonoWSQ *wsq;
1216
1217         EnterCriticalSection (&wsqs_lock);
1218         wsq = mono_wsq_create ();
1219         if (wsqs == NULL) {
1220                 LeaveCriticalSection (&wsqs_lock);
1221                 return NULL;
1222         }
1223         for (i = 0; i < wsqs->len; i++) {
1224                 if (g_ptr_array_index (wsqs, i) == NULL) {
1225                         wsqs->pdata [i] = wsq;
1226                         LeaveCriticalSection (&wsqs_lock);
1227                         return wsq;
1228                 }
1229         }
1230         g_ptr_array_add (wsqs, wsq);
1231         LeaveCriticalSection (&wsqs_lock);
1232         return wsq;
1233 }
1234
1235 static void
1236 remove_wsq (MonoWSQ *wsq)
1237 {
1238         gpointer data;
1239
1240         if (wsq == NULL)
1241                 return;
1242
1243         EnterCriticalSection (&wsqs_lock);
1244         if (wsqs == NULL) {
1245                 LeaveCriticalSection (&wsqs_lock);
1246                 return;
1247         }
1248         g_ptr_array_remove_fast (wsqs, wsq);
1249         data = NULL;
1250         /*
1251          * Only clean this up when shutting down, any other case will error out
1252          * if we're removing a queue that still has work items.
1253          */
1254         if (mono_runtime_is_shutting_down ()) {
1255                 while (mono_wsq_local_pop (&data)) {
1256                         threadpool_jobs_dec (data);
1257                         data = NULL;
1258                 }
1259         }
1260         mono_wsq_destroy (wsq);
1261         LeaveCriticalSection (&wsqs_lock);
1262 }
1263
1264 static void
1265 try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
1266 {
1267         int i;
1268         int ms;
1269
1270         if (wsqs == NULL || data == NULL || *data != NULL)
1271                 return;
1272
1273         ms = 0;
1274         do {
1275                 if (mono_runtime_is_shutting_down ())
1276                         return;
1277
1278                 EnterCriticalSection (&wsqs_lock);
1279                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1280                         MonoWSQ *wsq;
1281
1282                         wsq = wsqs->pdata [i];
1283                         if (wsq == local_wsq || mono_wsq_count (wsq) == 0)
1284                                 continue;
1285                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1286                         if (*data != NULL) {
1287                                 LeaveCriticalSection (&wsqs_lock);
1288                                 return;
1289                         }
1290                 }
1291                 LeaveCriticalSection (&wsqs_lock);
1292                 ms += 10;
1293         } while (retry && ms < 11);
1294 }
1295
1296 static gboolean
1297 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
1298 {
1299         if (mono_runtime_is_shutting_down ())
1300                 return FALSE;
1301         mono_cq_dequeue (tp->queue, (MonoObject **) data);
1302         if (!tp->is_io && !*data)
1303                 try_steal (local_wsq, data, FALSE);
1304         return (*data != NULL);
1305 }
1306
1307 static void
1308 process_idle_times (ThreadPool *tp, gint64 t)
1309 {
1310         gint64 ticks;
1311         gint64 avg;
1312         gboolean compute_avg;
1313         gint new_threads;
1314         gint64 per1;
1315
1316         if (tp->ignore_times || t <= 0)
1317                 return;
1318
1319         compute_avg = FALSE;
1320         ticks = mono_100ns_ticks ();
1321         t = ticks - t;
1322         SPIN_LOCK (tp->sp_lock);
1323         if (tp->ignore_times) {
1324                 SPIN_UNLOCK (tp->sp_lock);
1325                 return;
1326         }
1327         tp->time_sum += t;
1328         tp->n_sum++;
1329         if (tp->last_check == 0)
1330                 tp->last_check = ticks;
1331         else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1332                 tp->ignore_times = 1;
1333                 compute_avg = TRUE;
1334         }
1335         SPIN_UNLOCK (tp->sp_lock);
1336
1337         if (!compute_avg)
1338                 return;
1339
1340         //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1341         tp->last_check = ticks;
1342         new_threads = 0;
1343         avg = tp->time_sum / tp->n_sum;
1344         if (tp->averages [1] == 0) {
1345                 tp->averages [1] = avg;
1346         } else {
1347                 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1348                 if (per1 > 5) {
1349                         if (avg > tp->averages [1]) {
1350                                 if (tp->averages [1] < tp->averages [0]) {
1351                                         new_threads = -1;
1352                                 } else {
1353                                         new_threads = 1;
1354                                 }
1355                         } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1356                                 new_threads = 1;
1357                         }
1358                 } else {
1359                         int min, n;
1360                         min = tp->min_threads;
1361                         n = tp->nthreads;
1362                         if ((n - min) < min && tp->busy_threads == n)
1363                                 new_threads = 1;
1364                 }
1365                 /*
1366                 if (new_threads != 0) {
1367                         printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1368                 }
1369                 */
1370         }
1371
1372         tp->time_sum = 0;
1373         tp->n_sum = 0;
1374
1375         tp->averages [0] = tp->averages [1];
1376         tp->averages [1] = avg;
1377         tp->ignore_times = 0;
1378
1379         if (new_threads == -1) {
1380                 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1381                         pulse_on_new_job (tp);
1382         }
1383 }
1384
1385 static gboolean
1386 should_i_die (ThreadPool *tp)
1387 {
1388         gboolean result = FALSE;
1389         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1390                 result = (tp->nthreads > tp->min_threads);
1391         return result;
1392 }
1393
1394 static void
1395 async_invoke_thread (gpointer data)
1396 {
1397         MonoDomain *domain;
1398         MonoInternalThread *thread;
1399         MonoWSQ *wsq;
1400         ThreadPool *tp;
1401         gboolean must_die;
1402         const gchar *name;
1403   
1404         tp = data;
1405         wsq = NULL;
1406         if (!tp->is_io)
1407                 wsq = add_wsq ();
1408
1409         thread = mono_thread_internal_current ();
1410
1411         mono_profiler_thread_start (thread->tid);
1412         name = (tp->is_io) ? "IO Threadpool worker" : "Threadpool worker";
1413         mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), name), FALSE);
1414
1415         if (tp_start_func)
1416                 tp_start_func (tp_hooks_user_data);
1417
1418         data = NULL;
1419         for (;;) {
1420                 MonoAsyncResult *ar;
1421                 MonoClass *klass;
1422                 gboolean is_io_task;
1423                 gboolean is_socket;
1424                 int n_naps = 0;
1425
1426                 is_io_task = FALSE;
1427                 ar = (MonoAsyncResult *) data;
1428                 if (ar) {
1429                         InterlockedIncrement (&tp->busy_threads);
1430                         domain = ((MonoObject *)ar)->vtable->domain;
1431 #ifndef DISABLE_SOCKETS
1432                         klass = ((MonoObject *) data)->vtable->klass;
1433                         is_io_task = !is_corlib_asyncresult (domain, klass);
1434                         is_socket = FALSE;
1435                         if (is_io_task) {
1436                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1437                                 is_socket = is_socketasyncresult (domain, klass);
1438                                 ar = state->ares;
1439                                 switch (state->operation) {
1440                                 case AIO_OP_RECEIVE:
1441                                         state->total = ICALL_RECV (state);
1442                                         break;
1443                                 case AIO_OP_SEND:
1444                                         state->total = ICALL_SEND (state);
1445                                         break;
1446                                 }
1447                         }
1448 #endif
1449                         /* worker threads invokes methods in different domains,
1450                          * so we need to set the right domain here */
1451                         g_assert (domain);
1452
1453                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1454                                 threadpool_jobs_dec ((MonoObject *)ar);
1455                                 data = NULL;
1456                                 ar = NULL;
1457                                 InterlockedDecrement (&tp->busy_threads);
1458                         } else {
1459                                 mono_thread_push_appdomain_ref (domain);
1460                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1461                                         data = NULL;
1462                                         ar = NULL;
1463                                         mono_thread_pop_appdomain_ref ();
1464                                         InterlockedDecrement (&tp->busy_threads);
1465                                         continue;
1466                                 }
1467
1468                                 if (mono_domain_set (domain, FALSE)) {
1469                                         MonoObject *exc;
1470
1471                                         if (tp_item_begin_func)
1472                                                 tp_item_begin_func (tp_item_user_data);
1473
1474                                         if (!is_io_task && ar->add_time > 0)
1475                                                 process_idle_times (tp, ar->add_time);
1476                                         exc = mono_async_invoke (tp, ar);
1477                                         if (tp_item_end_func)
1478                                                 tp_item_end_func (tp_item_user_data);
1479                                         if (exc)
1480                                                 mono_internal_thread_unhandled_exception (exc);
1481                                         if (is_socket && tp->is_io) {
1482                                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1483
1484                                                 if (state->completed && state->callback) {
1485                                                         MonoAsyncResult *cb_ares;
1486                                                         cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
1487                                                                                                 (MonoObject *) state);
1488                                                         icall_append_job ((MonoObject *) cb_ares);
1489                                                 }
1490                                         }
1491                                         mono_domain_set (mono_get_root_domain (), TRUE);
1492                                 }
1493                                 mono_thread_pop_appdomain_ref ();
1494                                 InterlockedDecrement (&tp->busy_threads);
1495                                 /* If the callee changes the background status, set it back to TRUE */
1496                                 mono_thread_clr_state (thread , ~ThreadState_Background);
1497                                 if (!mono_thread_test_state (thread , ThreadState_Background))
1498                                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1499                         }
1500                 }
1501
1502                 ar = NULL;
1503                 data = NULL;
1504                 must_die = should_i_die (tp);
1505                 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
1506                         dequeue_or_steal (tp, &data, wsq);
1507
1508                 n_naps = 0;
1509                 while (!must_die && !data && n_naps < 4) {
1510                         gboolean res;
1511
1512                         InterlockedIncrement (&tp->waiting);
1513
1514                         // Another thread may have added a job into its wsq since the last call to dequeue_or_steal
1515                         // Check all the queues again before entering the wait loop
1516                         dequeue_or_steal (tp, &data, wsq);
1517                         if (data) {
1518                                 InterlockedDecrement (&tp->waiting);
1519                                 break;
1520                         }
1521
1522                         mono_gc_set_skip_thread (TRUE);
1523
1524 #if defined(__OpenBSD__)
1525                         while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
1526 #else
1527                         while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
1528 #endif
1529                                 if (mono_runtime_is_shutting_down ())
1530                                         break;
1531                                 if (THREAD_WANTS_A_BREAK (thread))
1532                                         mono_thread_interruption_checkpoint ();
1533                         }
1534                         InterlockedDecrement (&tp->waiting);
1535
1536                         mono_gc_set_skip_thread (FALSE);
1537
1538                         if (mono_runtime_is_shutting_down ())
1539                                 break;
1540                         must_die = should_i_die (tp);
1541                         dequeue_or_steal (tp, &data, wsq);
1542                         n_naps++;
1543                 }
1544
1545                 if (!data && !tp->is_io && !mono_runtime_is_shutting_down ()) {
1546                         mono_wsq_local_pop (&data);
1547                         if (data && must_die) {
1548                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
1549                                 pulse_on_new_job (tp);
1550                         }
1551                 }
1552
1553                 if (!data) {
1554                         gint nt;
1555                         gboolean down;
1556                         while (1) {
1557                                 nt = tp->nthreads;
1558                                 down = mono_runtime_is_shutting_down ();
1559                                 if (!down && nt <= tp->min_threads)
1560                                         break;
1561                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
1562 #ifndef DISABLE_PERFCOUNTERS
1563                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
1564 #endif
1565                                         if (!tp->is_io) {
1566                                                 remove_wsq (wsq);
1567                                         }
1568
1569                                         mono_profiler_thread_end (thread->tid);
1570
1571                                         if (tp_finish_func)
1572                                                 tp_finish_func (tp_hooks_user_data);
1573                                         return;
1574                                 }
1575                         }
1576                 }
1577         }
1578
1579         g_assert_not_reached ();
1580 }
1581
1582 void
1583 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1584 {
1585         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
1586         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
1587 }
1588
1589 void
1590 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1591 {
1592         *workerThreads = async_tp.max_threads;
1593         *completionPortThreads = async_io_tp.max_threads;
1594 }
1595
1596 void
1597 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1598 {
1599         *workerThreads = async_tp.min_threads;
1600         *completionPortThreads = async_io_tp.min_threads;
1601 }
1602
1603 MonoBoolean
1604 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1605 {
1606         gint max_threads;
1607         gint max_io_threads;
1608
1609         max_threads = async_tp.max_threads;
1610         if (workerThreads <= 0 || workerThreads > max_threads)
1611                 return FALSE;
1612
1613         max_io_threads = async_io_tp.max_threads;
1614         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
1615                 return FALSE;
1616
1617         InterlockedExchange (&async_tp.min_threads, workerThreads);
1618         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
1619         if (workerThreads > async_tp.nthreads)
1620                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE, FALSE, SMALL_STACK);
1621         if (completionPortThreads > async_io_tp.nthreads)
1622                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE, FALSE, SMALL_STACK);
1623         return TRUE;
1624 }
1625
1626 MonoBoolean
1627 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1628 {
1629         gint min_threads;
1630         gint min_io_threads;
1631         gint cpu_count;
1632
1633         cpu_count = mono_cpu_count ();
1634         min_threads = async_tp.min_threads;
1635         if (workerThreads < min_threads || workerThreads < cpu_count)
1636                 return FALSE;
1637
1638         /* We don't really have the concept of completion ports. Do we care here? */
1639         min_io_threads = async_io_tp.min_threads;
1640         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
1641                 return FALSE;
1642
1643         InterlockedExchange (&async_tp.max_threads, workerThreads);
1644         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
1645         return TRUE;
1646 }
1647
1648 /**
1649  * mono_install_threadpool_thread_hooks
1650  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
1651  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
1652  * @user_data: argument passed to @start_func and @finish_func.
1653  *
1654  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
1655  * The calls will be made from the thread itself.
1656  */
1657 void
1658 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
1659 {
1660         tp_start_func = start_func;
1661         tp_finish_func = finish_func;
1662         tp_hooks_user_data = user_data;
1663 }
1664
1665 /**
1666  * mono_install_threadpool_item_hooks
1667  * @begin_func: the function to be called before a threadpool work item processing starts.
1668  * @end_func: the function to be called after a threadpool work item is finished.
1669  * @user_data: argument passed to @begin_func and @end_func.
1670  *
1671  * The calls will be made from the thread itself and from the same AppDomain
1672  * where the work item was executed.
1673  *
1674  */
1675 void
1676 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
1677 {
1678         tp_item_begin_func = begin_func;
1679         tp_item_end_func = end_func;
1680         tp_item_user_data = user_data;
1681 }
1682
1683 void
1684 mono_internal_thread_unhandled_exception (MonoObject* exc)
1685 {
1686         if (mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
1687                 gboolean unloaded;
1688                 MonoClass *klass;
1689
1690                 klass = exc->vtable->klass;
1691                 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
1692                 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
1693                         mono_unhandled_exception (exc);
1694                         if (mono_environment_exitcode_get () == 1)
1695                                 exit (255);
1696                 }
1697                 if (klass == mono_defaults.threadabortexception_class)
1698                  mono_thread_internal_reset_abort (mono_thread_internal_current ());
1699         }
1700 }
1701
1702 /*
1703  * Suspend creation of new threads.
1704  */
1705 void
1706 mono_thread_pool_suspend (void)
1707 {
1708         suspended = TRUE;
1709 }
1710
1711 /*
1712  * Resume creation of new threads.
1713  */
1714 void
1715 mono_thread_pool_resume (void)
1716 {
1717         suspended = FALSE;
1718 }