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