ae687a62bd1a502d51802981e2b019d989d29b70
[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  */
11
12 #include <config.h>
13 #include <glib.h>
14
15 #ifdef MONO_SMALL_CONFIG
16 #define QUEUE_LENGTH 16 /* Must be 2^N */
17 #else
18 #define QUEUE_LENGTH 64 /* Must be 2^N */
19 #endif
20
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/profiler-private.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/threadpool-internals.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/file-io.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/mono-mlist.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/metadata/mono-perfcounters.h>
33 #include <mono/metadata/socket-io.h>
34 #include <mono/metadata/mono-wsq.h>
35 #include <mono/io-layer/io-layer.h>
36 #include <mono/metadata/gc-internal.h>
37 #include <mono/utils/mono-time.h>
38 #include <mono/utils/mono-proclib.h>
39 #include <mono/utils/mono-semaphore.h>
40 #include <errno.h>
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44 #include <sys/types.h>
45 #include <fcntl.h>
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49 #include <string.h>
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>
52 #endif
53 #include <mono/utils/mono-poll.h>
54 #ifdef HAVE_EPOLL
55 #include <sys/epoll.h>
56 #endif
57
58 #ifndef DISABLE_SOCKETS
59 #include "mono/io-layer/socket-wrappers.h"
60 #endif
61
62 #include "threadpool.h"
63
64 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
65                                                 ThreadState_SuspendRequested)) != 0)
66
67 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
68 #define SPIN_LOCK(i) do { \
69                                 if (SPIN_TRYLOCK (i)) \
70                                         break; \
71                         } while (1)
72
73 #define SPIN_UNLOCK(i) i = 0
74
75 #define EPOLL_DEBUG(...)
76 #define EPOLL_DEBUG_STMT(...)
77 #define TP_DEBUG(...)
78 #define TP_DEBUG_STMT(...)
79
80 /* DEBUG: prints tp data every 2s */
81 #undef DEBUG 
82
83 /*
84 #define EPOLL_DEBUG(...) g_message(__VA_ARGS__)
85 #define EPOLL_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
86 #define TP_DEBUG(...) g_message(__VA_ARGS__)
87 #define TP_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
88 */
89
90 /* map of CounterSample.cs */
91 struct _MonoCounterSample {
92         gint64 rawValue;
93         gint64 baseValue;
94         gint64 counterFrequency;
95         gint64 systemFrequency;
96         gint64 timeStamp;
97         gint64 timeStamp100nSec;
98         gint64 counterTimeStamp;
99         int counterType;
100 };
101
102 /* mono_thread_pool_init called */
103 static volatile int tp_inited;
104
105 typedef struct {
106         CRITICAL_SECTION io_lock; /* access to sock_to_state */
107         int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
108         int pipe [2];
109         MonoGHashTable *sock_to_state;
110
111         HANDLE new_sem; /* access to newpfd and write side of the pipe */
112         mono_pollfd *newpfd;
113         gboolean epoll_disabled;
114 #ifdef HAVE_EPOLL
115         int epollfd;
116 #endif
117 } SocketIOData;
118
119 static SocketIOData socket_io_data;
120
121 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
122 typedef struct {
123         MonoObject         object;
124         MonoMethodMessage *msg;
125         MonoMethod        *cb_method;
126         MonoDelegate      *cb_target;
127         MonoObject        *state;
128         MonoObject        *res;
129         MonoArray         *out_args;
130 } ASyncCall;
131
132 typedef struct {
133         MonoSemType lock;
134         MonoMList *first; /* GC root */
135         MonoMList *last;
136         MonoMList *unused; /* Up to 20 chunks. GC root */
137         gint head;
138         gint tail;
139         MonoSemType new_job;
140         volatile gint waiting; /* threads waiting for a work item */
141
142         /**/
143         volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
144         /* min, max, n and busy -> Interlocked */
145         volatile gint min_threads;
146         volatile gint max_threads;
147         volatile gint nthreads;
148         volatile gint busy_threads;
149
150         void (*async_invoke) (gpointer data);
151         void *pc_nitems; /* Performance counter for total number of items in added */
152         void *pc_nthreads; /* Performance counter for total number of active threads */
153         /**/
154         volatile gint destroy_thread;
155         volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
156         volatile gint sp_lock; /* spin lock used to protect ignore_times */
157         volatile gint64 last_check;
158         volatile gint64 time_sum;
159         volatile gint n_sum;
160         gint64 averages [2];
161         /**/
162         //TP_DEBUG_ONLY (gint nodes_created);
163         //TP_DEBUG_ONLY (gint nodes_reused);
164         gboolean is_io;
165 } ThreadPool;
166
167 static ThreadPool async_tp;
168 static ThreadPool async_io_tp;
169
170 static void async_invoke_thread (gpointer data);
171 static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
172 static void threadpool_free_queue (ThreadPool *tp);
173 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
174 static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
175 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
176 static void threadpool_start_idle_threads (ThreadPool *tp);
177 static void threadpool_kill_idle_threads (ThreadPool *tp);
178 static gboolean threadpool_start_thread (ThreadPool *tp);
179 static void monitor_thread (gpointer data);
180
181 static MonoClass *async_call_klass;
182 static MonoClass *socket_async_call_klass;
183 static MonoClass *process_async_call_klass;
184
185 static GPtrArray *wsqs;
186 CRITICAL_SECTION wsqs_lock;
187
188 /* Hooks */
189 static MonoThreadPoolFunc tp_start_func;
190 static MonoThreadPoolFunc tp_finish_func;
191 static gpointer tp_hooks_user_data;
192 static MonoThreadPoolItemFunc tp_item_begin_func;
193 static MonoThreadPoolItemFunc tp_item_end_func;
194 static gpointer tp_item_user_data;
195
196 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
197 enum {
198         AIO_OP_FIRST,
199         AIO_OP_ACCEPT = 0,
200         AIO_OP_CONNECT,
201         AIO_OP_RECEIVE,
202         AIO_OP_RECEIVEFROM,
203         AIO_OP_SEND,
204         AIO_OP_SENDTO,
205         AIO_OP_RECV_JUST_CALLBACK,
206         AIO_OP_SEND_JUST_CALLBACK,
207         AIO_OP_READPIPE,
208         AIO_OP_CONSOLE2,
209         AIO_OP_DISCONNECT,
210         AIO_OP_ACCEPTRECEIVE,
211         AIO_OP_RECEIVE_BUFFERS,
212         AIO_OP_SEND_BUFFERS,
213         AIO_OP_LAST
214 };
215
216 /*
217  * Functions to check whenever a class is given system class. We need to cache things in MonoDomain since some of the
218  * assemblies can be unloaded.
219  */
220
221 static gboolean
222 is_system_type (MonoDomain *domain, MonoClass *klass)
223 {
224         if (domain->system_image == NULL)
225                 domain->system_image = mono_image_loaded ("System");
226
227         return klass->image == domain->system_image;
228 }
229
230 static gboolean
231 is_corlib_type (MonoDomain *domain, MonoClass *klass)
232 {
233         return klass->image == mono_defaults.corlib;
234 }
235
236 /*
237  * Note that we call it is_socket_type() where 'socket' refers to the image
238  * that contains the System.Net.Sockets.Socket type.
239  * For moonlight there is a System.Net.Sockets.Socket class in both System.dll and System.Net.dll.
240 */
241 static gboolean
242 is_socket_type (MonoDomain *domain, MonoClass *klass)
243 {
244         static const char *version = NULL;
245         static gboolean moonlight;
246
247         if (is_system_type (domain, klass))
248                 return TRUE;
249
250         /* If moonlight, check if the type is in System.Net.dll too */
251         if (version == NULL) {
252                 version = mono_get_runtime_info ()->framework_version;
253                 moonlight = !strcmp (version, "2.1");
254         }
255
256         if (!moonlight)
257                 return FALSE;
258
259         if (domain->system_net_dll == NULL)
260                 domain->system_net_dll = mono_image_loaded ("System.Net");
261         
262         return klass->image == domain->system_net_dll;
263 }
264
265 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
266         if (*loc) \
267                 return *loc == _class; \
268         if (is_##ASSEMBLY##_type (domain, _class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
269                 *loc = _class; \
270                 return TRUE; \
271         } \
272         return FALSE; \
273 } while (0) \
274
275 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
276
277 #define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
278
279 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
280
281 static gboolean
282 is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
283 {
284         check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
285 }
286
287 static gboolean
288 is_socket (MonoDomain *domain, MonoClass *klass)
289 {
290         check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
291 }
292
293 static gboolean
294 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
295 {
296         return (klass->nested_in &&
297                         is_socket (domain, klass->nested_in) &&
298                         !strcmp (klass->name, "SocketAsyncResult"));
299 }
300
301 static gboolean
302 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
303 {
304         return (klass->nested_in &&
305                         is_socket (domain, klass->nested_in) &&
306                         !strcmp (klass->name, "SocketAsyncCall"));
307 }
308
309 static gboolean
310 is_appdomainunloaded_exception (MonoDomain *domain, MonoClass *klass)
311 {
312         check_corlib_type_cached (domain, klass, "System", "AppDomainUnloadedException", &domain->ad_unloaded_ex_class);
313 }
314
315 static gboolean
316 is_sd_process (MonoDomain *domain, MonoClass *klass)
317 {
318         check_system_type_cached (domain, klass, "System.Diagnostics", "Process", &domain->process_class);
319 }
320
321 static gboolean
322 is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
323 {
324
325         return (klass->nested_in &&
326                         is_sd_process (domain, klass->nested_in) &&
327                 !strcmp (klass->name, "AsyncReadHandler"));
328 }
329
330
331 #ifdef DISABLE_SOCKETS
332
333 #define socket_io_cleanup(x)
334
335 static int
336 get_event_from_state (MonoSocketAsyncResult *state)
337 {
338         g_assert_not_reached ();
339         return -1;
340 }
341
342 static int
343 get_events_from_list (MonoMList *list)
344 {
345         return 0;
346 }
347
348 #else
349
350 static void
351 socket_io_cleanup (SocketIOData *data)
352 {
353         EnterCriticalSection (&data->io_lock);
354         if (data->inited != 2) {
355                 LeaveCriticalSection (&data->io_lock);
356                 return;
357         }
358         data->inited = 3;
359
360 #ifdef HOST_WIN32
361         closesocket (data->pipe [0]);
362         closesocket (data->pipe [1]);
363 #else
364         if (data->pipe [0] > -1)
365                 close (data->pipe [0]);
366         if (data->pipe [1] > -1)
367                 close (data->pipe [1]);
368 #endif
369         data->pipe [0] = -1;
370         data->pipe [1] = -1;
371         if (data->new_sem)
372                 CloseHandle (data->new_sem);
373         data->new_sem = NULL;
374         mono_g_hash_table_destroy (data->sock_to_state);
375         data->sock_to_state = NULL;
376         g_free (data->newpfd);
377         data->newpfd = NULL;
378 #ifdef HAVE_EPOLL
379         if (FALSE == data->epoll_disabled)
380                 close (data->epollfd);
381 #endif
382         LeaveCriticalSection (&data->io_lock);
383 }
384
385 static int
386 get_event_from_state (MonoSocketAsyncResult *state)
387 {
388         switch (state->operation) {
389         case AIO_OP_ACCEPT:
390         case AIO_OP_RECEIVE:
391         case AIO_OP_RECV_JUST_CALLBACK:
392         case AIO_OP_RECEIVEFROM:
393         case AIO_OP_READPIPE:
394         case AIO_OP_ACCEPTRECEIVE:
395         case AIO_OP_RECEIVE_BUFFERS:
396                 return MONO_POLLIN;
397         case AIO_OP_SEND:
398         case AIO_OP_SEND_JUST_CALLBACK:
399         case AIO_OP_SENDTO:
400         case AIO_OP_CONNECT:
401         case AIO_OP_SEND_BUFFERS:
402         case AIO_OP_DISCONNECT:
403                 return MONO_POLLOUT;
404         default: /* Should never happen */
405                 g_message ("get_event_from_state: unknown value in switch!!!");
406                 return 0;
407         }
408 }
409
410 static int
411 get_events_from_list (MonoMList *list)
412 {
413         MonoSocketAsyncResult *state;
414         int events = 0;
415
416         while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
417                 events |= get_event_from_state (state);
418                 list = mono_mlist_next (list);
419         }
420
421         return events;
422 }
423
424 #define ICALL_RECV(x)   ves_icall_System_Net_Sockets_Socket_Receive_internal (\
425                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
426                                  x->socket_flags, &x->error);
427
428 #define ICALL_SEND(x)   ves_icall_System_Net_Sockets_Socket_Send_internal (\
429                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
430                                  x->socket_flags, &x->error);
431
432 #endif /* !DISABLE_SOCKETS */
433
434 static void
435 threadpool_jobs_inc (MonoObject *obj)
436 {
437         if (obj)
438                 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
439 }
440
441 static gboolean
442 threadpool_jobs_dec (MonoObject *obj)
443 {
444         MonoDomain *domain = obj->vtable->domain;
445         int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
446         if (remaining_jobs == 0 && domain->cleanup_semaphore) {
447                 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
448                 return TRUE;
449         }
450         return FALSE;
451 }
452
453 #ifdef HAVE_EPOLL
454 static MonoObject *
455 get_io_event (MonoMList **list, gint event)
456 {
457         MonoObject *state;
458         MonoMList *current;
459         MonoMList *prev;
460
461         current = *list;
462         prev = NULL;
463         state = NULL;
464         while (current) {
465                 state = mono_mlist_get_data (current);
466                 if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
467                         break;
468
469                 state = NULL;
470                 prev = current;
471                 current = mono_mlist_next (current);
472         }
473
474         if (current) {
475                 if (prev) {
476                         mono_mlist_set_next (prev, mono_mlist_next (current));
477                 } else {
478                         *list = mono_mlist_next (*list);
479                 }
480         }
481
482         return state;
483 }
484 #endif
485
486 static MonoMList *
487 process_io_event (MonoMList *list, int event)
488 {
489         MonoSocketAsyncResult *state;
490         MonoMList *oldlist;
491
492         oldlist = list;
493         state = NULL;
494         while (list) {
495                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
496                 if (get_event_from_state (state) == event)
497                         break;
498                 
499                 list = mono_mlist_next (list);
500         }
501
502         if (list != NULL) {
503                 oldlist = mono_mlist_remove_item (oldlist, list);
504                 EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
505                 threadpool_append_job (&async_io_tp, (MonoObject *) state);
506         }
507
508         return oldlist;
509 }
510
511 static int
512 mark_bad_fds (mono_pollfd *pfds, int nfds)
513 {
514         int i, ret;
515         mono_pollfd *pfd;
516         int count = 0;
517
518         for (i = 0; i < nfds; i++) {
519                 pfd = &pfds [i];
520                 if (pfd->fd == -1)
521                         continue;
522
523                 ret = mono_poll (pfd, 1, 0);
524                 if (ret == -1 && errno == EBADF) {
525                         pfd->revents |= MONO_POLLNVAL;
526                         count++;
527                 } else if (ret == 1) {
528                         count++;
529                 }
530         }
531
532         return count;
533 }
534
535 static void
536 socket_io_poll_main (gpointer p)
537 {
538 #if MONO_SMALL_CONFIG
539 #define INITIAL_POLLFD_SIZE     128
540 #else
541 #define INITIAL_POLLFD_SIZE     1024
542 #endif
543 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
544         SocketIOData *data = p;
545         mono_pollfd *pfds;
546         gint maxfd = 1;
547         gint allocated;
548         gint i;
549         MonoInternalThread *thread;
550
551         thread = mono_thread_internal_current ();
552
553         allocated = INITIAL_POLLFD_SIZE;
554         pfds = g_new0 (mono_pollfd, allocated);
555         INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
556         for (i = 1; i < allocated; i++)
557                 INIT_POLLFD (&pfds [i], -1, 0);
558
559         while (1) {
560                 int nsock = 0;
561                 mono_pollfd *pfd;
562                 char one [1];
563                 MonoMList *list;
564
565                 do {
566                         if (nsock == -1) {
567                                 if (THREAD_WANTS_A_BREAK (thread))
568                                         mono_thread_interruption_checkpoint ();
569                         }
570
571                         nsock = mono_poll (pfds, maxfd, -1);
572                 } while (nsock == -1 && errno == EINTR);
573
574                 /* 
575                  * Apart from EINTR, we only check EBADF, for the rest:
576                  *  EINVAL: mono_poll() 'protects' us from descriptor
577                  *      numbers above the limit if using select() by marking
578                  *      then as MONO_POLLERR.  If a system poll() is being
579                  *      used, the number of descriptor we're passing will not
580                  *      be over sysconf(_SC_OPEN_MAX), as the error would have
581                  *      happened when opening.
582                  *
583                  *  EFAULT: we own the memory pointed by pfds.
584                  *  ENOMEM: we're doomed anyway
585                  *
586                  */
587
588                 if (nsock == -1 && errno == EBADF) {
589                         pfds->revents = 0; /* Just in case... */
590                         nsock = mark_bad_fds (pfds, maxfd);
591                 }
592
593                 if ((pfds->revents & POLL_ERRORS) != 0) {
594                         /* We're supposed to die now, as the pipe has been closed */
595                         g_free (pfds);
596                         socket_io_cleanup (data);
597                         return;
598                 }
599
600                 /* Got a new socket */
601                 if ((pfds->revents & MONO_POLLIN) != 0) {
602                         int nread;
603
604                         for (i = 1; i < allocated; i++) {
605                                 pfd = &pfds [i];
606                                 if (pfd->fd == -1 || data->newpfd == NULL ||
607                                         pfd->fd == data->newpfd->fd)
608                                         break;
609                         }
610
611                         if (i == allocated) {
612                                 mono_pollfd *oldfd;
613
614                                 oldfd = pfds;
615                                 i = allocated;
616                                 allocated = allocated * 2;
617                                 pfds = g_renew (mono_pollfd, oldfd, allocated);
618                                 g_free (oldfd);
619                                 for (; i < allocated; i++)
620                                         INIT_POLLFD (&pfds [i], -1, 0);
621                         }
622 #ifndef HOST_WIN32
623                         nread = read (data->pipe [0], one, 1);
624 #else
625                         nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
626 #endif
627                         if (nread <= 0) {
628                                 g_free (pfds);
629                                 return; /* we're closed */
630                         }
631
632                         INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
633                         ReleaseSemaphore (data->new_sem, 1, NULL);
634                         if (i >= maxfd)
635                                 maxfd = i + 1;
636                         nsock--;
637                 }
638
639                 if (nsock == 0)
640                         continue;
641
642                 EnterCriticalSection (&data->io_lock);
643                 if (data->inited == 3) {
644                         g_free (pfds);
645                         LeaveCriticalSection (&data->io_lock);
646                         return; /* cleanup called */
647                 }
648
649                 for (i = 1; i < maxfd && nsock > 0; i++) {
650                         pfd = &pfds [i];
651                         if (pfd->fd == -1 || pfd->revents == 0)
652                                 continue;
653
654                         nsock--;
655                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
656                         if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
657                                 list = process_io_event (list, MONO_POLLIN);
658                         }
659
660                         if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
661                                 list = process_io_event (list, MONO_POLLOUT);
662                         }
663
664                         if (list != NULL) {
665                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
666                                 pfd->events = get_events_from_list (list);
667                         } else {
668                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
669                                 pfd->fd = -1;
670                                 if (i == maxfd - 1)
671                                         maxfd--;
672                         }
673                 }
674                 LeaveCriticalSection (&data->io_lock);
675         }
676 }
677
678 #ifdef HAVE_EPOLL
679 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
680 #define EPOLL_NEVENTS   128
681 static void
682 socket_io_epoll_main (gpointer p)
683 {
684         SocketIOData *data;
685         int epollfd;
686         MonoInternalThread *thread;
687         struct epoll_event *events, *evt;
688         int ready = 0, i;
689         gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
690         gint nresults;
691
692         data = p;
693         epollfd = data->epollfd;
694         thread = mono_thread_internal_current ();
695         events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
696
697         while (1) {
698                 do {
699                         if (ready == -1) {
700                                 if (THREAD_WANTS_A_BREAK (thread))
701                                         mono_thread_interruption_checkpoint ();
702                         }
703                         EPOLL_DEBUG ("epoll_wait init");
704                         ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
705                         EPOLL_DEBUG_STMT(
706                                 int err = errno;
707                                 EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
708                                 errno = err;
709                         );
710                 } while (ready == -1 && errno == EINTR);
711
712                 if (ready == -1) {
713                         int err = errno;
714                         g_free (events);
715                         if (err != EBADF)
716                                 g_warning ("epoll_wait: %d %s", err, g_strerror (err));
717
718                         close (epollfd);
719                         return;
720                 }
721
722                 EnterCriticalSection (&data->io_lock);
723                 if (data->inited == 3) {
724                         g_free (events);
725                         close (epollfd);
726                         LeaveCriticalSection (&data->io_lock);
727                         return; /* cleanup called */
728                 }
729
730                 nresults = 0;
731                 for (i = 0; i < ready; i++) {
732                         int fd;
733                         MonoMList *list;
734                         MonoObject *ares;
735
736                         evt = &events [i];
737                         fd = evt->data.fd;
738                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
739                         EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
740                         if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
741                                 ares = get_io_event (&list, MONO_POLLIN);
742                                 if (ares != NULL)
743                                         async_results [nresults++] = ares;
744                         }
745
746                         if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
747                                 ares = get_io_event (&list, MONO_POLLOUT);
748                                 if (ares != NULL)
749                                         async_results [nresults++] = ares;
750                         }
751
752                         if (list != NULL) {
753                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
754                                 evt->events = get_events_from_list (list);
755                                 EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
756                                 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
757                                         if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
758                                                 EPOLL_DEBUG_STMT (
759                                                         int err = errno;
760                                                         EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
761                                                         errno = err;
762                                                 );
763                                         }
764                                 }
765                         } else {
766                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
767                                 EPOLL_DEBUG ("DEL %d", fd);
768                                 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
769                         }
770                 }
771                 LeaveCriticalSection (&data->io_lock);
772                 threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
773                 memset (async_results, 0, sizeof (gpointer) * nresults);
774         }
775 }
776 #undef EPOLL_NEVENTS
777 #endif
778
779 /*
780  * select/poll wake up when a socket is closed, but epoll just removes
781  * the socket from its internal list without notification.
782  */
783 void
784 mono_thread_pool_remove_socket (int sock)
785 {
786         MonoMList *list, *next;
787         MonoSocketAsyncResult *state;
788
789         if (socket_io_data.inited == 0)
790                 return;
791
792         EnterCriticalSection (&socket_io_data.io_lock);
793         if (socket_io_data.sock_to_state == NULL) {
794                 LeaveCriticalSection (&socket_io_data.io_lock);
795                 return;
796         }
797         list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
798         if (list)
799                 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
800         LeaveCriticalSection (&socket_io_data.io_lock);
801         
802         while (list) {
803                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
804                 if (state->operation == AIO_OP_RECEIVE)
805                         state->operation = AIO_OP_RECV_JUST_CALLBACK;
806                 else if (state->operation == AIO_OP_SEND)
807                         state->operation = AIO_OP_SEND_JUST_CALLBACK;
808
809                 next = mono_mlist_remove_item (list, list);
810                 list = process_io_event (list, MONO_POLLIN);
811                 if (list)
812                         process_io_event (list, MONO_POLLOUT);
813
814                 list = next;
815         }
816 }
817
818 #ifdef HOST_WIN32
819 static void
820 connect_hack (gpointer x)
821 {
822         struct sockaddr_in *addr = (struct sockaddr_in *) x;
823         int count = 0;
824
825         while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
826                 Sleep (500);
827                 if (++count > 3) {
828                         g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
829                         g_assert (WSAGetLastError ());
830                 }
831         }
832 }
833 #endif
834
835 static void
836 socket_io_init (SocketIOData *data)
837 {
838 #ifdef HOST_WIN32
839         struct sockaddr_in server;
840         struct sockaddr_in client;
841         SOCKET srv;
842         int len;
843 #endif
844         int inited;
845         guint32 stack_size;
846
847         if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
848                 return;
849
850         inited = InterlockedCompareExchange (&data->inited, 1, 0);
851         if (inited >= 1) {
852                 while (TRUE) {
853                         if (data->inited >= 2)
854                                 return;
855                         SleepEx (1, FALSE);
856                 }
857         }
858
859         EnterCriticalSection (&data->io_lock);
860
861 #ifdef HAVE_EPOLL
862         data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
863         if (FALSE == data->epoll_disabled) {
864                 data->epollfd = epoll_create (256);
865                 data->epoll_disabled = (data->epollfd == -1);
866                 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
867                         g_message ("epoll_create() failed. Using plain poll().");
868         } else {
869                 data->epollfd = -1;
870         }
871 #else
872         data->epoll_disabled = TRUE;
873 #endif
874
875 #ifndef HOST_WIN32
876         if (data->epoll_disabled) {
877                 if (pipe (data->pipe) != 0) {
878                         int err = errno;
879                         perror ("mono");
880                         g_assert (err);
881                 }
882         } else {
883                 data->pipe [0] = -1;
884                 data->pipe [1] = -1;
885         }
886 #else
887         srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
888         g_assert (srv != INVALID_SOCKET);
889         data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
890         g_assert (data->pipe [1] != INVALID_SOCKET);
891
892         server.sin_family = AF_INET;
893         server.sin_addr.s_addr = inet_addr ("127.0.0.1");
894         server.sin_port = 0;
895         if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
896                 g_print ("%d\n", WSAGetLastError ());
897                 g_assert (1 != 0);
898         }
899
900         len = sizeof (server);
901         getsockname (srv, (SOCKADDR *) &server, &len);
902         listen (srv, 1);
903         mono_thread_create (mono_get_root_domain (), connect_hack, &server);
904         len = sizeof (server);
905         data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
906         g_assert (data->pipe [0] != INVALID_SOCKET);
907         closesocket (srv);
908 #endif
909         data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
910
911         if (data->epoll_disabled) {
912                 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
913                 g_assert (data->new_sem != NULL);
914         }
915
916         stack_size = mono_threads_get_default_stacksize ();
917         /* 128k stacks could lead to problems on 64 bit systems with large pagesizes+altstack */
918         mono_threads_set_default_stacksize (128 * (sizeof (gpointer) / 4) * 1024);
919         if (data->epoll_disabled) {
920                 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
921         }
922 #ifdef HAVE_EPOLL
923         else {
924                 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
925         }
926 #endif
927         mono_threads_set_default_stacksize (stack_size);
928         LeaveCriticalSection (&data->io_lock);
929         data->inited = 2;
930 }
931
932 static void
933 socket_io_add_poll (MonoSocketAsyncResult *state)
934 {
935         int events;
936         char msg [1];
937         MonoMList *list;
938         SocketIOData *data = &socket_io_data;
939         int w;
940
941         if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
942                 return;
943
944 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
945         /* select() for connect() does not work well on the Mac. Bug #75436. */
946         /* Bug #77637 for the BSD 6 case */
947         /* Bug #78888 for the Windows case */
948         if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
949                 //FIXME: increment number of threads while this one is waiting?
950                 threadpool_append_job (&async_io_tp, (MonoObject *) state);
951                 return;
952         }
953 #endif
954         WaitForSingleObject (data->new_sem, INFINITE);
955         if (data->newpfd == NULL)
956                 data->newpfd = g_new0 (mono_pollfd, 1);
957
958         EnterCriticalSection (&data->io_lock);
959         if (data->sock_to_state == NULL) {
960                 LeaveCriticalSection (&data->io_lock);
961                 return;
962         }
963
964         /* FIXME: 64 bit issue: handle can be a pointer on windows? */
965         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
966         if (list == NULL) {
967                 list = mono_mlist_alloc ((MonoObject*)state);
968         } else {
969                 list = mono_mlist_append (list, (MonoObject*)state);
970         }
971
972         events = get_events_from_list (list);
973         INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
974         mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
975         LeaveCriticalSection (&data->io_lock);
976         *msg = (char) state->operation;
977 #ifndef HOST_WIN32
978         w = write (data->pipe [1], msg, 1);
979         w = w;
980 #else
981         send ((SOCKET) data->pipe [1], msg, 1, 0);
982 #endif
983 }
984
985 #ifdef HAVE_EPOLL
986 static gboolean
987 socket_io_add_epoll (MonoSocketAsyncResult *state)
988 {
989         MonoMList *list;
990         SocketIOData *data = &socket_io_data;
991         struct epoll_event event;
992         int epoll_op, ievt;
993         int fd;
994
995         if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
996                 return TRUE;
997
998         memset (&event, 0, sizeof (struct epoll_event));
999         fd = GPOINTER_TO_INT (state->handle);
1000         EnterCriticalSection (&data->io_lock);
1001         if (data->sock_to_state == NULL) {
1002                 LeaveCriticalSection (&data->io_lock);
1003                 return TRUE;
1004         }
1005         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
1006         if (list == NULL) {
1007                 list = mono_mlist_alloc ((MonoObject*)state);
1008                 epoll_op = EPOLL_CTL_ADD;
1009         } else {
1010                 list = mono_mlist_append (list, (MonoObject*)state);
1011                 epoll_op = EPOLL_CTL_MOD;
1012         }
1013
1014         ievt = get_events_from_list (list);
1015         if ((ievt & MONO_POLLIN) != 0)
1016                 event.events |= EPOLLIN;
1017         if ((ievt & MONO_POLLOUT) != 0)
1018                 event.events |= EPOLLOUT;
1019
1020         mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
1021         event.data.fd = fd;
1022         EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
1023         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
1024                 int err = errno;
1025                 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
1026                         epoll_op = EPOLL_CTL_MOD;
1027                         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
1028                                 g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
1029                         }
1030                 }
1031         }
1032         LeaveCriticalSection (&data->io_lock);
1033
1034         return TRUE;
1035 }
1036 #endif
1037
1038 static void
1039 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
1040 {
1041         if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
1042                 return;
1043
1044         socket_io_init (&socket_io_data);
1045
1046         MONO_OBJECT_SETREF (state, ares, ares);
1047 #ifdef HAVE_EPOLL
1048         if (socket_io_data.epoll_disabled == FALSE) {
1049                 if (socket_io_add_epoll (state))
1050                         return;
1051         }
1052 #endif
1053         socket_io_add_poll (state);
1054 }
1055
1056 #ifndef DISABLE_SOCKETS
1057 static gboolean
1058 socket_io_filter (MonoObject *target, MonoObject *state)
1059 {
1060         gint op;
1061         MonoSocketAsyncResult *sock_res;
1062         MonoClass *klass;
1063         MonoDomain *domain;
1064
1065         if (target == NULL || state == NULL)
1066                 return FALSE;
1067
1068         domain = target->vtable->domain;
1069         klass = target->vtable->klass;
1070         if (socket_async_call_klass == NULL && is_socketasynccall (domain, klass))
1071                 socket_async_call_klass = klass;
1072
1073         if (process_async_call_klass == NULL && is_sdp_asyncreadhandler (domain, klass))
1074                 process_async_call_klass = klass;
1075
1076         if (klass != socket_async_call_klass && klass != process_async_call_klass)
1077                 return FALSE;
1078
1079         sock_res = (MonoSocketAsyncResult *) state;
1080         op = sock_res->operation;
1081         if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
1082                 return FALSE;
1083
1084         return TRUE;
1085 }
1086 #endif /* !DISABLE_SOCKETS */
1087
1088 /* Returns the exception thrown when invoking, if any */
1089 static MonoObject *
1090 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
1091 {
1092         ASyncCall *ac = (ASyncCall *)ares->object_data;
1093         MonoObject *res, *exc = NULL;
1094         MonoArray *out_args = NULL;
1095         HANDLE wait_event = NULL;
1096
1097         if (ares->execution_context) {
1098                 /* use captured ExecutionContext (if available) */
1099                 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
1100                 mono_thread_set_execution_context (ares->execution_context);
1101         } else {
1102                 ares->original_context = NULL;
1103         }
1104
1105         if (ac == NULL) {
1106                 /* Fast path from ThreadPool.*QueueUserWorkItem */
1107                 void *pa = ares->async_state;
1108                 mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
1109         } else {
1110                 MonoObject *cb_exc = NULL;
1111
1112                 ac->msg->exc = NULL;
1113                 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
1114                 MONO_OBJECT_SETREF (ac, res, res);
1115                 MONO_OBJECT_SETREF (ac, msg->exc, exc);
1116                 MONO_OBJECT_SETREF (ac, out_args, out_args);
1117
1118                 mono_monitor_enter ((MonoObject *) ares);
1119                 ares->completed = 1;
1120                 if (ares->handle != NULL)
1121                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1122                 mono_monitor_exit ((MonoObject *) ares);
1123                 /* notify listeners */
1124                 if (wait_event != NULL)
1125                         SetEvent (wait_event);
1126
1127                 /* call async callback if cb_method != null*/
1128                 if (ac != NULL && ac->cb_method) {
1129                         void *pa = &ares;
1130                         cb_exc = NULL;
1131                         mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
1132                         MONO_OBJECT_SETREF (ac->msg, exc, cb_exc);
1133                         exc = cb_exc;
1134                 } else {
1135                         exc = NULL;
1136                 }
1137         }
1138
1139         /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1140         if (ares->original_context) {
1141                 mono_thread_set_execution_context (ares->original_context);
1142                 ares->original_context = NULL;
1143         }
1144         return exc;
1145 }
1146
1147 static void
1148 threadpool_start_idle_threads (ThreadPool *tp)
1149 {
1150         int n;
1151
1152         if (tp->pool_status == 1 && !tp->is_io)
1153                 mono_thread_create_internal (mono_get_root_domain (), monitor_thread, tp, TRUE);
1154         do {
1155                 while (1) {
1156                         n = tp->nthreads;
1157                         if (n >= tp->min_threads)
1158                                 return;
1159                         if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
1160                                 break;
1161                 }
1162                 mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1163                 mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1164                 SleepEx (100, TRUE);
1165         } while (1);
1166 }
1167
1168 static void
1169 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
1170 {
1171         memset (tp, 0, sizeof (ThreadPool));
1172         MONO_SEM_INIT (&tp->lock, 1);
1173         tp->min_threads = min_threads;
1174         tp->max_threads = max_threads;
1175         tp->async_invoke = async_invoke;
1176         MONO_SEM_INIT (&tp->new_job, 0);
1177 }
1178
1179 static void *
1180 init_perf_counter (const char *category, const char *counter)
1181 {
1182         MonoString *category_str;
1183         MonoString *counter_str;
1184         MonoString *machine;
1185         MonoDomain *root;
1186         MonoBoolean custom;
1187         int type;
1188
1189         if (category == NULL || counter == NULL)
1190                 return NULL;
1191         root = mono_get_root_domain ();
1192         category_str = mono_string_new (root, category);
1193         counter_str = mono_string_new (root, counter);
1194         machine = mono_string_new (root, ".");
1195         return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
1196 }
1197
1198 #ifdef DEBUG
1199 static void
1200 print_pool_info (ThreadPool *tp)
1201 {
1202
1203 //      if (tp->tail - tp->head == 0)
1204 //              return;
1205
1206         g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
1207         g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
1208         g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
1209         g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
1210         g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
1211         g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
1212         g_print ("Queued: %d\n", (tp->tail - tp->head));
1213         if (tp == &async_tp) {
1214                 int i;
1215                 EnterCriticalSection (&wsqs_lock);
1216                 for (i = 0; i < wsqs->len; i++) {
1217                         g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
1218                 }
1219                 LeaveCriticalSection (&wsqs_lock);
1220         } else {
1221                 g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
1222         }
1223         g_print ("-------------\n");
1224 }
1225
1226 static void
1227 signal_handler (int signo)
1228 {
1229         ThreadPool *tp;
1230
1231         tp = &async_tp;
1232         MONO_SEM_WAIT (&tp->lock);
1233         g_print ("\n-----Non-IO-----\n");
1234         print_pool_info (tp);
1235         MONO_SEM_POST (&tp->lock);
1236         tp = &async_io_tp;
1237         MONO_SEM_WAIT (&tp->lock);
1238         g_print ("\n-----IO-----\n");
1239         print_pool_info (tp);
1240         MONO_SEM_POST (&tp->lock);
1241         alarm (2);
1242 }
1243 #endif
1244
1245 static void
1246 monitor_thread (gpointer data)
1247 {
1248         ThreadPool *tp;
1249         MonoInternalThread *thread;
1250         guint32 ms;
1251         gboolean need_one;
1252         int i;
1253
1254         tp = data;
1255         thread = mono_thread_internal_current ();
1256         while (1) {
1257                 ms = 500;
1258                 do {
1259                         guint32 ts;
1260                         ts = mono_msec_ticks ();
1261                         if (SleepEx (ms, TRUE) == 0)
1262                                 break;
1263                         ms -= (mono_msec_ticks () - ts);
1264                         if (mono_runtime_is_shutting_down ())
1265                                 break;
1266                         if (THREAD_WANTS_A_BREAK (thread))
1267                                 mono_thread_interruption_checkpoint ();
1268                 } while (ms > 0);
1269
1270                 if (mono_runtime_is_shutting_down ())
1271                         break;
1272                 if (tp->waiting > 0)
1273                         continue;
1274                 MONO_SEM_WAIT (&tp->lock);
1275                 need_one = (tp->head != tp->tail);
1276                 if (!need_one) {
1277                         EnterCriticalSection (&wsqs_lock);
1278                         for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1279                                 MonoWSQ *wsq;
1280                                 wsq = g_ptr_array_index (wsqs, i);
1281                                 if (mono_wsq_count (wsq) > 0) {
1282                                         need_one = TRUE;
1283                                         break;
1284                                 }
1285                         }
1286                         LeaveCriticalSection (&wsqs_lock);
1287                 }
1288                 MONO_SEM_POST (&tp->lock);
1289                 if (need_one)
1290                         threadpool_start_thread (tp);
1291         }
1292 }
1293
1294 void
1295 mono_thread_pool_init ()
1296 {
1297         gint threads_per_cpu = 1;
1298         gint thread_count;
1299         gint cpu_count = mono_cpu_count ();
1300         int result;
1301
1302         if (tp_inited == 2)
1303                 return;
1304
1305         result = InterlockedCompareExchange (&tp_inited, 1, 0);
1306         if (result == 1) {
1307                 while (1) {
1308                         SleepEx (1, FALSE);
1309                         if (tp_inited == 2)
1310                                 return;
1311                 }
1312         }
1313
1314         MONO_GC_REGISTER_ROOT_SINGLE (async_tp.first);
1315         MONO_GC_REGISTER_ROOT_SINGLE (async_tp.last);
1316         MONO_GC_REGISTER_ROOT_SINGLE (async_tp.unused);
1317         MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.first);
1318         MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.unused);
1319         MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.last);
1320
1321         MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
1322         InitializeCriticalSection (&socket_io_data.io_lock);
1323         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1324                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1325                 if (threads_per_cpu < 1)
1326                         threads_per_cpu = 1;
1327         }
1328
1329         thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1330         threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1331         threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1332         async_io_tp.is_io = TRUE;
1333
1334         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1335         g_assert (async_call_klass);
1336
1337         InitializeCriticalSection (&wsqs_lock);
1338         wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1339         mono_wsq_init ();
1340
1341         async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1342         g_assert (async_tp.pc_nitems);
1343
1344         async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1345         g_assert (async_io_tp.pc_nitems);
1346
1347         async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1348         g_assert (async_tp.pc_nthreads);
1349
1350         async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1351         g_assert (async_io_tp.pc_nthreads);
1352         tp_inited = 2;
1353 #ifdef DEBUG
1354         signal (SIGALRM, signal_handler);
1355         alarm (2);
1356 #endif
1357 }
1358
1359 static MonoAsyncResult *
1360 create_simple_asyncresult (MonoObject *target, MonoObject *state)
1361 {
1362         MonoDomain *domain = mono_domain_get ();
1363         MonoAsyncResult *ares;
1364
1365         /* Don't call mono_async_result_new() to avoid capturing the context */
1366         ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1367         MONO_OBJECT_SETREF (ares, async_delegate, target);
1368         MONO_OBJECT_SETREF (ares, async_state, state);
1369         return ares;
1370 }
1371
1372 void
1373 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1374 {
1375         MonoAsyncResult *ares;
1376
1377         ares = create_simple_asyncresult (target, (MonoObject *) state);
1378         socket_io_add (ares, state);
1379 }
1380
1381 MonoAsyncResult *
1382 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1383                       MonoObject *state)
1384 {
1385         MonoDomain *domain = mono_domain_get ();
1386         MonoAsyncResult *ares;
1387         ASyncCall *ac;
1388
1389         ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1390         MONO_OBJECT_SETREF (ac, msg, msg);
1391         MONO_OBJECT_SETREF (ac, state, state);
1392
1393         if (async_callback) {
1394                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1395                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1396         }
1397
1398         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1399         MONO_OBJECT_SETREF (ares, async_delegate, target);
1400
1401 #ifndef DISABLE_SOCKETS
1402         if (socket_io_filter (target, state)) {
1403                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1404                 return ares;
1405         }
1406 #endif
1407         threadpool_append_job (&async_tp, (MonoObject *) ares);
1408         return ares;
1409 }
1410
1411 MonoObject *
1412 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1413 {
1414         ASyncCall *ac;
1415         HANDLE wait_event;
1416
1417         *exc = NULL;
1418         *out_args = NULL;
1419
1420         /* check if already finished */
1421         mono_monitor_enter ((MonoObject *) ares);
1422         
1423         if (ares->endinvoke_called) {
1424                 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1425                 mono_monitor_exit ((MonoObject *) ares);
1426                 return NULL;
1427         }
1428
1429         ares->endinvoke_called = 1;
1430         /* wait until we are really finished */
1431         if (!ares->completed) {
1432                 if (ares->handle == NULL) {
1433                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1434                         g_assert(wait_event != 0);
1435                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1436                 } else {
1437                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1438                 }
1439                 mono_monitor_exit ((MonoObject *) ares);
1440                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1441         } else {
1442                 mono_monitor_exit ((MonoObject *) ares);
1443         }
1444
1445         ac = (ASyncCall *) ares->object_data;
1446         g_assert (ac != NULL);
1447         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1448         *out_args = ac->out_args;
1449
1450         return ac->res;
1451 }
1452
1453 static void
1454 threadpool_kill_idle_threads (ThreadPool *tp)
1455 {
1456         gint n;
1457
1458         n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1459         while (n) {
1460                 n--;
1461                 MONO_SEM_POST (&tp->new_job);
1462         }
1463 }
1464
1465 void
1466 mono_thread_pool_cleanup (void)
1467 {
1468         if (!(async_tp.pool_status == 0 || async_tp.pool_status == 2)) {
1469                 if (!(async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)) {
1470                         InterlockedExchange (&async_io_tp.pool_status, 2);
1471                         MONO_SEM_WAIT (&async_tp.lock);
1472                         threadpool_free_queue (&async_tp);
1473                         threadpool_kill_idle_threads (&async_tp);
1474                         MONO_SEM_POST (&async_tp.lock);
1475
1476                         socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1477                         MONO_SEM_WAIT (&async_io_tp.lock);
1478                         threadpool_free_queue (&async_io_tp);
1479                         threadpool_kill_idle_threads (&async_io_tp);
1480                         MONO_SEM_POST (&async_io_tp.lock);
1481                         MONO_SEM_DESTROY (&async_io_tp.new_job);
1482                 }
1483         }
1484
1485         EnterCriticalSection (&wsqs_lock);
1486         mono_wsq_cleanup ();
1487         if (wsqs)
1488                 g_ptr_array_free (wsqs, TRUE);
1489         wsqs = NULL;
1490         LeaveCriticalSection (&wsqs_lock);
1491         MONO_SEM_DESTROY (&async_tp.new_job);
1492 }
1493
1494 /* Caller must enter &tp->lock */
1495 static MonoObject*
1496 dequeue_job_nolock (ThreadPool *tp)
1497 {
1498         MonoObject *ar;
1499         MonoArray *array;
1500         MonoMList *list;
1501
1502         list = tp->first;
1503         do {
1504                 if (mono_runtime_is_shutting_down ())
1505                         return NULL;
1506                 if (!list || tp->head == tp->tail)
1507                         return NULL;
1508
1509                 array = (MonoArray *) mono_mlist_get_data (list);
1510                 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1511                 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1512                 tp->head++;
1513                 if ((tp->head % QUEUE_LENGTH) == 0) {
1514                         list = tp->first;
1515                         tp->first = mono_mlist_next (list);
1516                         if (tp->first == NULL)
1517                                 tp->last = NULL;
1518                         if (mono_mlist_length (tp->unused) < 20) {
1519                                 /* reuse this chunk */
1520                                 tp->unused = mono_mlist_set_next (list, tp->unused);
1521                         }
1522                         tp->head -= QUEUE_LENGTH;
1523                         tp->tail -= QUEUE_LENGTH;
1524                 }
1525                 list = tp->first;
1526         } while (ar == NULL);
1527         return ar;
1528 }
1529
1530 static gboolean
1531 threadpool_start_thread (ThreadPool *tp)
1532 {
1533         gint n;
1534
1535         while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1536                 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1537                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1538                         mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1539                         return TRUE;
1540                 }
1541         }
1542
1543         return FALSE;
1544 }
1545
1546 static void
1547 pulse_on_new_job (ThreadPool *tp)
1548 {
1549         if (tp->waiting)
1550                 MONO_SEM_POST (&tp->new_job);
1551 }
1552
1553 void
1554 icall_append_job (MonoObject *ar)
1555 {
1556         threadpool_append_job (&async_tp, ar);
1557 }
1558
1559 static void
1560 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1561 {
1562         threadpool_append_jobs (tp, &ar, 1);
1563 }
1564
1565 static MonoMList *
1566 create_or_reuse_list (ThreadPool *tp)
1567 {
1568         MonoMList *list;
1569         MonoArray *array;
1570
1571         list = NULL;
1572         if (tp->unused) {
1573                 list = tp->unused;
1574                 tp->unused = mono_mlist_next (list);
1575                 mono_mlist_set_next (list, NULL);
1576                 //TP_DEBUG (tp->nodes_reused++);
1577         } else {
1578                 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1579                 list = mono_mlist_alloc ((MonoObject *) array);
1580                 //TP_DEBUG (tp->nodes_created++);
1581         }
1582         return list;
1583 }
1584
1585 static void
1586 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1587 {
1588         static int job_counter;
1589         MonoArray *array;
1590         MonoMList *list;
1591         MonoObject *ar;
1592         gint i;
1593         gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1594
1595         if (mono_runtime_is_shutting_down ())
1596                 return;
1597
1598         if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1599                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1600
1601         for (i = 0; i < njobs; i++) {
1602                 ar = jobs [i];
1603                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1604                         continue; /* Might happen when cleaning domain jobs */
1605                 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1606                         MonoAsyncResult *o = (MonoAsyncResult *) ar;
1607                         o->add_time = mono_100ns_ticks ();
1608                 }
1609                 threadpool_jobs_inc (ar); 
1610                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1611                 if (!tp->is_io && mono_wsq_local_push (ar))
1612                         continue;
1613
1614                 if (!lock_taken) {
1615                         MONO_SEM_WAIT (&tp->lock);
1616                         lock_taken = TRUE;
1617                 }
1618                 if ((tp->tail % QUEUE_LENGTH) == 0) {
1619                         list = create_or_reuse_list (tp);
1620                         if (tp->last != NULL)
1621                                 mono_mlist_set_next (tp->last, list);
1622                         tp->last = list;
1623                         if (tp->first == NULL)
1624                                 tp->first = tp->last;
1625                 }
1626
1627                 array = (MonoArray *) mono_mlist_get_data (tp->last);
1628                 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1629                 tp->tail++;
1630         }
1631         if (lock_taken)
1632                 MONO_SEM_POST (&tp->lock);
1633
1634         for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1635                 pulse_on_new_job (tp);
1636 }
1637
1638 static void
1639 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1640 {
1641         MonoMList *current;
1642         MonoArray *array;
1643         MonoObject *obj;
1644         int domain_count;
1645         int i;
1646
1647         domain_count = 0;
1648         MONO_SEM_WAIT (&tp->lock);
1649         current = tp->first;
1650         while (current) {
1651                 array = (MonoArray *) mono_mlist_get_data (current);
1652                 for (i = 0; i < QUEUE_LENGTH; i++) {
1653                         obj = mono_array_get (array, MonoObject*, i);
1654                         if (obj != NULL && obj->vtable->domain == domain) {
1655                                 domain_count++;
1656                                 mono_array_setref (array, i, NULL);
1657                                 threadpool_jobs_dec (obj);
1658                         }
1659                 }
1660                 current = mono_mlist_next (current);
1661         }
1662
1663         if (!domain_count) {
1664                 MONO_SEM_POST (&tp->lock);
1665                 return;
1666         }
1667
1668         current = tp->first;
1669         tp->first = NULL;
1670         tp->last = NULL;
1671         tp->head = 0;
1672         tp->tail = 0;
1673         MONO_SEM_POST (&tp->lock);
1674         /* Re-add everything but the nullified elements */
1675         while (current) {
1676                 array = (MonoArray *) mono_mlist_get_data (current);
1677                 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1678                 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1679                 current = mono_mlist_next (current);
1680         }
1681 }
1682
1683 /*
1684  * Clean up the threadpool of all domain jobs.
1685  * Can only be called as part of the domain unloading process as
1686  * it will wait for all jobs to be visible to the interruption code. 
1687  */
1688 gboolean
1689 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1690 {
1691         HANDLE sem_handle;
1692         int result = TRUE;
1693         guint32 start_time = 0;
1694
1695         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1696
1697         threadpool_clear_queue (&async_tp, domain);
1698         threadpool_clear_queue (&async_io_tp, domain);
1699
1700         /*
1701          * There might be some threads out that could be about to execute stuff from the given domain.
1702          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1703          */
1704         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1705
1706         domain->cleanup_semaphore = sem_handle;
1707         /*
1708          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1709          * and reading threadpool_jobs.
1710          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1711          */
1712         mono_memory_write_barrier ();
1713
1714         if (domain->threadpool_jobs && timeout != -1)
1715                 start_time = mono_msec_ticks ();
1716         while (domain->threadpool_jobs) {
1717                 WaitForSingleObject (sem_handle, timeout);
1718                 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1719                         result = FALSE;
1720                         break;
1721                 }
1722         }
1723
1724         domain->cleanup_semaphore = NULL;
1725         CloseHandle (sem_handle);
1726         return result;
1727 }
1728
1729 static void
1730 threadpool_free_queue (ThreadPool *tp)
1731 {
1732         tp->head = tp->tail = 0;
1733         tp->first = NULL;
1734         tp->unused = NULL;
1735 }
1736
1737 gboolean
1738 mono_thread_pool_is_queue_array (MonoArray *o)
1739 {
1740         gpointer obj = o;
1741
1742         // FIXME: need some fix in sgen code.
1743         // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1744         return obj == async_tp.first || obj == async_io_tp.first;
1745 }
1746
1747 static MonoWSQ *
1748 add_wsq (void)
1749 {
1750         int i;
1751         MonoWSQ *wsq;
1752
1753         EnterCriticalSection (&wsqs_lock);
1754         wsq = mono_wsq_create ();
1755         if (wsqs == NULL) {
1756                 LeaveCriticalSection (&wsqs_lock);
1757                 return NULL;
1758         }
1759         for (i = 0; i < wsqs->len; i++) {
1760                 if (g_ptr_array_index (wsqs, i) == NULL) {
1761                         wsqs->pdata [i] = wsq;
1762                         LeaveCriticalSection (&wsqs_lock);
1763                         return wsq;
1764                 }
1765         }
1766         g_ptr_array_add (wsqs, wsq);
1767         LeaveCriticalSection (&wsqs_lock);
1768         return wsq;
1769 }
1770
1771 static void
1772 remove_wsq (MonoWSQ *wsq)
1773 {
1774         gpointer data;
1775
1776         if (wsq == NULL)
1777                 return;
1778
1779         EnterCriticalSection (&wsqs_lock);
1780         if (wsqs == NULL) {
1781                 LeaveCriticalSection (&wsqs_lock);
1782                 return;
1783         }
1784         g_ptr_array_remove_fast (wsqs, wsq);
1785         data = NULL;
1786         while (mono_wsq_local_pop (&data)) {
1787                 threadpool_jobs_dec (data);
1788                 data = NULL;
1789         }
1790         mono_wsq_destroy (wsq);
1791         LeaveCriticalSection (&wsqs_lock);
1792 }
1793
1794 static void
1795 try_steal (gpointer *data, gboolean retry)
1796 {
1797         int i;
1798         int ms;
1799
1800         if (wsqs == NULL || data == NULL || *data != NULL)
1801                 return;
1802
1803         ms = 0;
1804         do {
1805                 if (mono_runtime_is_shutting_down ())
1806                         return;
1807                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1808                         if (mono_runtime_is_shutting_down ()) {
1809                                 return;
1810                         }
1811                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1812                         if (*data != NULL) {
1813                                 return;
1814                         }
1815                 }
1816                 ms += 10;
1817         } while (retry && ms < 11);
1818 }
1819
1820 static gboolean
1821 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1822 {
1823         if (mono_runtime_is_shutting_down ())
1824                 return FALSE;
1825         TP_DEBUG ("Dequeue");
1826         MONO_SEM_WAIT (&tp->lock);
1827         *data = dequeue_job_nolock (tp);
1828         MONO_SEM_POST (&tp->lock);
1829         if (!tp->is_io && !*data)
1830                 try_steal (data, FALSE);
1831         return (*data != NULL);
1832 }
1833
1834 static void
1835 process_idle_times (ThreadPool *tp, gint64 t)
1836 {
1837         gint64 ticks;
1838         gint64 avg;
1839         gboolean compute_avg;
1840         gint new_threads;
1841         gint64 per1;
1842
1843         if (tp->ignore_times || t <= 0)
1844                 return;
1845
1846         compute_avg = FALSE;
1847         ticks = mono_100ns_ticks ();
1848         t = ticks - t;
1849         SPIN_LOCK (tp->sp_lock);
1850         if (tp->ignore_times) {
1851                 SPIN_UNLOCK (tp->sp_lock);
1852                 return;
1853         }
1854         tp->time_sum += t;
1855         tp->n_sum++;
1856         if (tp->last_check == 0)
1857                 tp->last_check = ticks;
1858         else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1859                 tp->ignore_times = 1;
1860                 compute_avg = TRUE;
1861         }
1862         SPIN_UNLOCK (tp->sp_lock);
1863
1864         if (!compute_avg)
1865                 return;
1866
1867         //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1868         tp->last_check = ticks;
1869         new_threads = 0;
1870         avg = tp->time_sum / tp->n_sum;
1871         if (tp->averages [1] == 0) {
1872                 tp->averages [1] = avg;
1873         } else {
1874                 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1875                 if (per1 > 5) {
1876                         if (avg > tp->averages [1]) {
1877                                 if (tp->averages [1] < tp->averages [0]) {
1878                                         new_threads = -1;
1879                                 } else {
1880                                         new_threads = 1;
1881                                 }
1882                         } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1883                                 new_threads = 1;
1884                         }
1885                 } else {
1886                         int min, n;
1887                         min = tp->min_threads;
1888                         n = tp->nthreads;
1889                         if ((n - min) < min && tp->busy_threads == n)
1890                                 new_threads = 1;
1891                 }
1892                 /*
1893                 if (new_threads != 0) {
1894                         printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1895                 }
1896                 */
1897         }
1898
1899         tp->time_sum = 0;
1900         tp->n_sum = 0;
1901
1902         tp->averages [0] = tp->averages [1];
1903         tp->averages [1] = avg;
1904         tp->ignore_times = 0;
1905
1906         if (new_threads == -1) {
1907                 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1908                         pulse_on_new_job (tp);
1909         }
1910 }
1911
1912 static gboolean
1913 should_i_die (ThreadPool *tp)
1914 {
1915         gboolean result = FALSE;
1916         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1917                 result = (tp->nthreads > tp->min_threads);
1918         return result;
1919 }
1920
1921 static void
1922 async_invoke_thread (gpointer data)
1923 {
1924         MonoDomain *domain;
1925         MonoInternalThread *thread;
1926         MonoWSQ *wsq;
1927         ThreadPool *tp;
1928         gboolean must_die;
1929   
1930         tp = data;
1931         wsq = NULL;
1932         if (!tp->is_io)
1933                 wsq = add_wsq ();
1934
1935         thread = mono_thread_internal_current ();
1936
1937         mono_profiler_thread_start (thread->tid);
1938
1939         if (tp_start_func)
1940                 tp_start_func (tp_hooks_user_data);
1941
1942         data = NULL;
1943         for (;;) {
1944                 MonoAsyncResult *ar;
1945                 MonoClass *klass;
1946                 gboolean is_io_task;
1947                 gboolean is_socket;
1948                 int n_naps = 0;
1949
1950                 is_io_task = FALSE;
1951                 ar = (MonoAsyncResult *) data;
1952                 if (ar) {
1953                         InterlockedIncrement (&tp->busy_threads);
1954                         domain = ((MonoObject *)ar)->vtable->domain;
1955 #ifndef DISABLE_SOCKET
1956                         klass = ((MonoObject *) data)->vtable->klass;
1957                         is_io_task = !is_corlib_asyncresult (domain, klass);
1958                         is_socket = FALSE;
1959                         if (is_io_task) {
1960                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1961                                 is_socket = is_socketasyncresult (domain, klass);
1962                                 ar = state->ares;
1963                                 switch (state->operation) {
1964                                 case AIO_OP_RECEIVE:
1965                                         state->total = ICALL_RECV (state);
1966                                         break;
1967                                 case AIO_OP_SEND:
1968                                         state->total = ICALL_SEND (state);
1969                                         break;
1970                                 }
1971                         }
1972 #endif
1973                         /* worker threads invokes methods in different domains,
1974                          * so we need to set the right domain here */
1975                         g_assert (domain);
1976
1977                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1978                                 threadpool_jobs_dec ((MonoObject *)ar);
1979                                 data = NULL;
1980                                 ar = NULL;
1981                                 InterlockedDecrement (&tp->busy_threads);
1982                         } else {
1983                                 mono_thread_push_appdomain_ref (domain);
1984                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1985                                         data = NULL;
1986                                         ar = NULL;
1987                                         mono_thread_pop_appdomain_ref ();
1988                                         InterlockedDecrement (&tp->busy_threads);
1989                                         continue;
1990                                 }
1991
1992                                 if (mono_domain_set (domain, FALSE)) {
1993                                         MonoObject *exc;
1994
1995                                         if (tp_item_begin_func)
1996                                                 tp_item_begin_func (tp_item_user_data);
1997
1998                                         if (!is_io_task && ar->add_time > 0)
1999                                                 process_idle_times (tp, ar->add_time);
2000                                         exc = mono_async_invoke (tp, ar);
2001                                         if (tp_item_end_func)
2002                                                 tp_item_end_func (tp_item_user_data);
2003                                         if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
2004                                                 gboolean unloaded;
2005                                                 MonoClass *klass;
2006
2007                                                 klass = exc->vtable->klass;
2008                                                 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
2009                                                 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
2010                                                         mono_unhandled_exception (exc);
2011                                                         exit (255);
2012                                                 }
2013                                         }
2014                                         if (is_socket && tp->is_io) {
2015                                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
2016
2017                                                 if (state->completed && state->callback) {
2018                                                         MonoAsyncResult *cb_ares;
2019                                                         cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
2020                                                                                                 (MonoObject *) state);
2021                                                         icall_append_job ((MonoObject *) cb_ares);
2022                                                 }
2023                                         }
2024                                         mono_domain_set (mono_get_root_domain (), TRUE);
2025                                 }
2026                                 mono_thread_pop_appdomain_ref ();
2027                                 InterlockedDecrement (&tp->busy_threads);
2028                                 /* If the callee changes the background status, set it back to TRUE */
2029                                 mono_thread_clr_state (thread , ~ThreadState_Background);
2030                                 if (!mono_thread_test_state (thread , ThreadState_Background))
2031                                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
2032                         }
2033                 }
2034
2035                 ar = NULL;
2036                 data = NULL;
2037                 must_die = should_i_die (tp);
2038                 TP_DEBUG ("Trying to get a job");
2039                 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
2040                         dequeue_or_steal (tp, &data);
2041                 TP_DEBUG ("Done trying to get a job %p", data);
2042
2043                 n_naps = 0;
2044                 while (!must_die && !data && n_naps < 4) {
2045                         gboolean res;
2046
2047                         TP_DEBUG ("Waiting");
2048                         InterlockedIncrement (&tp->waiting);
2049 #if defined(__OpenBSD__)
2050                         while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
2051 #else
2052                         while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
2053 #endif
2054                                 if (mono_runtime_is_shutting_down ())
2055                                         break;
2056                                 if (THREAD_WANTS_A_BREAK (thread))
2057                                         mono_thread_interruption_checkpoint ();
2058                         }
2059                         TP_DEBUG ("Done waiting");
2060                         InterlockedDecrement (&tp->waiting);
2061                         if (mono_runtime_is_shutting_down ())
2062                                 break;
2063                         must_die = should_i_die (tp);
2064                         dequeue_or_steal (tp, &data);
2065                         n_naps++;
2066                 }
2067
2068                 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
2069                         mono_wsq_local_pop (&data);
2070                         if (data && must_die) {
2071                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
2072                                 pulse_on_new_job (tp);
2073                         }
2074                 }
2075
2076                 if (!data) {
2077                         gint nt;
2078                         gboolean down;
2079                         while (1) {
2080                                 nt = tp->nthreads;
2081                                 down = mono_runtime_is_shutting_down ();
2082                                 if (!down && nt <= tp->min_threads)
2083                                         break;
2084                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
2085                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
2086                                         TP_DEBUG ("DIE");
2087                                         if (!tp->is_io) {
2088                                                 remove_wsq (wsq);
2089                                         }
2090
2091                                         mono_profiler_thread_end (thread->tid);
2092
2093                                         if (tp_finish_func)
2094                                                 tp_finish_func (tp_hooks_user_data);
2095                                         return;
2096                                 }
2097                         }
2098                 }
2099         }
2100
2101         g_assert_not_reached ();
2102 }
2103
2104 void
2105 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
2106 {
2107         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
2108         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
2109 }
2110
2111 void
2112 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
2113 {
2114         *workerThreads = async_tp.max_threads;
2115         *completionPortThreads = async_io_tp.max_threads;
2116 }
2117
2118 void
2119 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
2120 {
2121         *workerThreads = async_tp.min_threads;
2122         *completionPortThreads = async_io_tp.min_threads;
2123 }
2124
2125 MonoBoolean
2126 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
2127 {
2128         gint max_threads;
2129         gint max_io_threads;
2130
2131         max_threads = async_tp.max_threads;
2132         if (workerThreads <= 0 || workerThreads > max_threads)
2133                 return FALSE;
2134
2135         max_io_threads = async_io_tp.max_threads;
2136         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
2137                 return FALSE;
2138
2139         InterlockedExchange (&async_tp.min_threads, workerThreads);
2140         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
2141         if (workerThreads > async_tp.nthreads)
2142                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
2143         if (completionPortThreads > async_io_tp.nthreads)
2144                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
2145         return TRUE;
2146 }
2147
2148 MonoBoolean
2149 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
2150 {
2151         gint min_threads;
2152         gint min_io_threads;
2153         gint cpu_count;
2154
2155         cpu_count = mono_cpu_count ();
2156         min_threads = async_tp.min_threads;
2157         if (workerThreads < min_threads || workerThreads < cpu_count)
2158                 return FALSE;
2159
2160         /* We don't really have the concept of completion ports. Do we care here? */
2161         min_io_threads = async_io_tp.min_threads;
2162         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2163                 return FALSE;
2164
2165         InterlockedExchange (&async_tp.max_threads, workerThreads);
2166         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2167         return TRUE;
2168 }
2169
2170 /**
2171  * mono_install_threadpool_thread_hooks
2172  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2173  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2174  * @user_data: argument passed to @start_func and @finish_func.
2175  *
2176  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2177  * The calls will be made from the thread itself.
2178  */
2179 void
2180 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2181 {
2182         tp_start_func = start_func;
2183         tp_finish_func = finish_func;
2184         tp_hooks_user_data = user_data;
2185 }
2186
2187 /**
2188  * mono_install_threadpool_item_hooks
2189  * @begin_func: the function to be called before a threadpool work item processing starts.
2190  * @end_func: the function to be called after a threadpool work item is finished.
2191  * @user_data: argument passed to @begin_func and @end_func.
2192  *
2193  * The calls will be made from the thread itself and from the same AppDomain
2194  * where the work item was executed.
2195  *
2196  */
2197 void
2198 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2199 {
2200         tp_item_begin_func = begin_func;
2201         tp_item_end_func = end_func;
2202         tp_item_user_data = user_data;
2203 }
2204