253402a31cbf524d01a5a2d19e094b6165f11215
[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         ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threapool monitor"));
1257         while (1) {
1258                 ms = 500;
1259                 do {
1260                         guint32 ts;
1261                         ts = mono_msec_ticks ();
1262                         if (SleepEx (ms, TRUE) == 0)
1263                                 break;
1264                         ms -= (mono_msec_ticks () - ts);
1265                         if (mono_runtime_is_shutting_down ())
1266                                 break;
1267                         if (THREAD_WANTS_A_BREAK (thread))
1268                                 mono_thread_interruption_checkpoint ();
1269                 } while (ms > 0);
1270
1271                 if (mono_runtime_is_shutting_down ())
1272                         break;
1273                 if (tp->waiting > 0)
1274                         continue;
1275                 MONO_SEM_WAIT (&tp->lock);
1276                 need_one = (tp->head != tp->tail);
1277                 if (!need_one) {
1278                         EnterCriticalSection (&wsqs_lock);
1279                         for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1280                                 MonoWSQ *wsq;
1281                                 wsq = g_ptr_array_index (wsqs, i);
1282                                 if (mono_wsq_count (wsq) > 0) {
1283                                         need_one = TRUE;
1284                                         break;
1285                                 }
1286                         }
1287                         LeaveCriticalSection (&wsqs_lock);
1288                 }
1289                 MONO_SEM_POST (&tp->lock);
1290                 if (need_one)
1291                         threadpool_start_thread (tp);
1292         }
1293 }
1294
1295 void
1296 mono_thread_pool_init ()
1297 {
1298         gint threads_per_cpu = 1;
1299         gint thread_count;
1300         gint cpu_count = mono_cpu_count ();
1301         int result;
1302
1303         if (tp_inited == 2)
1304                 return;
1305
1306         result = InterlockedCompareExchange (&tp_inited, 1, 0);
1307         if (result == 1) {
1308                 while (1) {
1309                         SleepEx (1, FALSE);
1310                         if (tp_inited == 2)
1311                                 return;
1312                 }
1313         }
1314
1315         MONO_GC_REGISTER_ROOT_SINGLE (async_tp.first);
1316         MONO_GC_REGISTER_ROOT_SINGLE (async_tp.last);
1317         MONO_GC_REGISTER_ROOT_SINGLE (async_tp.unused);
1318         MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.first);
1319         MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.unused);
1320         MONO_GC_REGISTER_ROOT_SINGLE (async_io_tp.last);
1321
1322         MONO_GC_REGISTER_ROOT_FIXED (socket_io_data.sock_to_state);
1323         InitializeCriticalSection (&socket_io_data.io_lock);
1324         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1325                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1326                 if (threads_per_cpu < 1)
1327                         threads_per_cpu = 1;
1328         }
1329
1330         thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
1331         threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
1332         threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
1333         async_io_tp.is_io = TRUE;
1334
1335         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1336         g_assert (async_call_klass);
1337
1338         InitializeCriticalSection (&wsqs_lock);
1339         wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
1340         mono_wsq_init ();
1341
1342         async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
1343         g_assert (async_tp.pc_nitems);
1344
1345         async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
1346         g_assert (async_io_tp.pc_nitems);
1347
1348         async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
1349         g_assert (async_tp.pc_nthreads);
1350
1351         async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
1352         g_assert (async_io_tp.pc_nthreads);
1353         tp_inited = 2;
1354 #ifdef DEBUG
1355         signal (SIGALRM, signal_handler);
1356         alarm (2);
1357 #endif
1358 }
1359
1360 static MonoAsyncResult *
1361 create_simple_asyncresult (MonoObject *target, MonoObject *state)
1362 {
1363         MonoDomain *domain = mono_domain_get ();
1364         MonoAsyncResult *ares;
1365
1366         /* Don't call mono_async_result_new() to avoid capturing the context */
1367         ares = (MonoAsyncResult *) mono_object_new (domain, mono_defaults.asyncresult_class);
1368         MONO_OBJECT_SETREF (ares, async_delegate, target);
1369         MONO_OBJECT_SETREF (ares, async_state, state);
1370         return ares;
1371 }
1372
1373 void
1374 icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
1375 {
1376         MonoAsyncResult *ares;
1377
1378         ares = create_simple_asyncresult (target, (MonoObject *) state);
1379         socket_io_add (ares, state);
1380 }
1381
1382 MonoAsyncResult *
1383 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1384                       MonoObject *state)
1385 {
1386         MonoDomain *domain = mono_domain_get ();
1387         MonoAsyncResult *ares;
1388         ASyncCall *ac;
1389
1390         ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
1391         MONO_OBJECT_SETREF (ac, msg, msg);
1392         MONO_OBJECT_SETREF (ac, state, state);
1393
1394         if (async_callback) {
1395                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1396                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1397         }
1398
1399         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1400         MONO_OBJECT_SETREF (ares, async_delegate, target);
1401
1402 #ifndef DISABLE_SOCKETS
1403         if (socket_io_filter (target, state)) {
1404                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1405                 return ares;
1406         }
1407 #endif
1408         threadpool_append_job (&async_tp, (MonoObject *) ares);
1409         return ares;
1410 }
1411
1412 MonoObject *
1413 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1414 {
1415         ASyncCall *ac;
1416         HANDLE wait_event;
1417
1418         *exc = NULL;
1419         *out_args = NULL;
1420
1421         /* check if already finished */
1422         mono_monitor_enter ((MonoObject *) ares);
1423         
1424         if (ares->endinvoke_called) {
1425                 *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
1426                 mono_monitor_exit ((MonoObject *) ares);
1427                 return NULL;
1428         }
1429
1430         ares->endinvoke_called = 1;
1431         /* wait until we are really finished */
1432         if (!ares->completed) {
1433                 if (ares->handle == NULL) {
1434                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1435                         g_assert(wait_event != 0);
1436                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1437                 } else {
1438                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1439                 }
1440                 mono_monitor_exit ((MonoObject *) ares);
1441                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1442         } else {
1443                 mono_monitor_exit ((MonoObject *) ares);
1444         }
1445
1446         ac = (ASyncCall *) ares->object_data;
1447         g_assert (ac != NULL);
1448         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1449         *out_args = ac->out_args;
1450
1451         return ac->res;
1452 }
1453
1454 static void
1455 threadpool_kill_idle_threads (ThreadPool *tp)
1456 {
1457         gint n;
1458
1459         n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
1460         while (n) {
1461                 n--;
1462                 MONO_SEM_POST (&tp->new_job);
1463         }
1464 }
1465
1466 void
1467 mono_thread_pool_cleanup (void)
1468 {
1469         if (!(async_tp.pool_status == 0 || async_tp.pool_status == 2)) {
1470                 if (!(async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)) {
1471                         InterlockedExchange (&async_io_tp.pool_status, 2);
1472                         MONO_SEM_WAIT (&async_tp.lock);
1473                         threadpool_free_queue (&async_tp);
1474                         threadpool_kill_idle_threads (&async_tp);
1475                         MONO_SEM_POST (&async_tp.lock);
1476
1477                         socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
1478                         MONO_SEM_WAIT (&async_io_tp.lock);
1479                         threadpool_free_queue (&async_io_tp);
1480                         threadpool_kill_idle_threads (&async_io_tp);
1481                         MONO_SEM_POST (&async_io_tp.lock);
1482                         MONO_SEM_DESTROY (&async_io_tp.new_job);
1483                 }
1484         }
1485
1486         EnterCriticalSection (&wsqs_lock);
1487         mono_wsq_cleanup ();
1488         if (wsqs)
1489                 g_ptr_array_free (wsqs, TRUE);
1490         wsqs = NULL;
1491         LeaveCriticalSection (&wsqs_lock);
1492         MONO_SEM_DESTROY (&async_tp.new_job);
1493 }
1494
1495 /* Caller must enter &tp->lock */
1496 static MonoObject*
1497 dequeue_job_nolock (ThreadPool *tp)
1498 {
1499         MonoObject *ar;
1500         MonoArray *array;
1501         MonoMList *list;
1502
1503         list = tp->first;
1504         do {
1505                 if (mono_runtime_is_shutting_down ())
1506                         return NULL;
1507                 if (!list || tp->head == tp->tail)
1508                         return NULL;
1509
1510                 array = (MonoArray *) mono_mlist_get_data (list);
1511                 ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
1512                 mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
1513                 tp->head++;
1514                 if ((tp->head % QUEUE_LENGTH) == 0) {
1515                         list = tp->first;
1516                         tp->first = mono_mlist_next (list);
1517                         if (tp->first == NULL)
1518                                 tp->last = NULL;
1519                         if (mono_mlist_length (tp->unused) < 20) {
1520                                 /* reuse this chunk */
1521                                 tp->unused = mono_mlist_set_next (list, tp->unused);
1522                         }
1523                         tp->head -= QUEUE_LENGTH;
1524                         tp->tail -= QUEUE_LENGTH;
1525                 }
1526                 list = tp->first;
1527         } while (ar == NULL);
1528         return ar;
1529 }
1530
1531 static gboolean
1532 threadpool_start_thread (ThreadPool *tp)
1533 {
1534         gint n;
1535
1536         while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
1537                 if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
1538                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
1539                         mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
1540                         return TRUE;
1541                 }
1542         }
1543
1544         return FALSE;
1545 }
1546
1547 static void
1548 pulse_on_new_job (ThreadPool *tp)
1549 {
1550         if (tp->waiting)
1551                 MONO_SEM_POST (&tp->new_job);
1552 }
1553
1554 void
1555 icall_append_job (MonoObject *ar)
1556 {
1557         threadpool_append_job (&async_tp, ar);
1558 }
1559
1560 static void
1561 threadpool_append_job (ThreadPool *tp, MonoObject *ar)
1562 {
1563         threadpool_append_jobs (tp, &ar, 1);
1564 }
1565
1566 static MonoMList *
1567 create_or_reuse_list (ThreadPool *tp)
1568 {
1569         MonoMList *list;
1570         MonoArray *array;
1571
1572         list = NULL;
1573         if (tp->unused) {
1574                 list = tp->unused;
1575                 tp->unused = mono_mlist_next (list);
1576                 mono_mlist_set_next (list, NULL);
1577                 //TP_DEBUG (tp->nodes_reused++);
1578         } else {
1579                 array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
1580                 list = mono_mlist_alloc ((MonoObject *) array);
1581                 //TP_DEBUG (tp->nodes_created++);
1582         }
1583         return list;
1584 }
1585
1586 static void
1587 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
1588 {
1589         static int job_counter;
1590         MonoArray *array;
1591         MonoMList *list;
1592         MonoObject *ar;
1593         gint i;
1594         gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
1595
1596         if (mono_runtime_is_shutting_down ())
1597                 return;
1598
1599         if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
1600                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
1601
1602         for (i = 0; i < njobs; i++) {
1603                 ar = jobs [i];
1604                 if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
1605                         continue; /* Might happen when cleaning domain jobs */
1606                 if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
1607                         MonoAsyncResult *o = (MonoAsyncResult *) ar;
1608                         o->add_time = mono_100ns_ticks ();
1609                 }
1610                 threadpool_jobs_inc (ar); 
1611                 mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
1612                 if (!tp->is_io && mono_wsq_local_push (ar))
1613                         continue;
1614
1615                 if (!lock_taken) {
1616                         MONO_SEM_WAIT (&tp->lock);
1617                         lock_taken = TRUE;
1618                 }
1619                 if ((tp->tail % QUEUE_LENGTH) == 0) {
1620                         list = create_or_reuse_list (tp);
1621                         if (tp->last != NULL)
1622                                 mono_mlist_set_next (tp->last, list);
1623                         tp->last = list;
1624                         if (tp->first == NULL)
1625                                 tp->first = tp->last;
1626                 }
1627
1628                 array = (MonoArray *) mono_mlist_get_data (tp->last);
1629                 mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
1630                 tp->tail++;
1631         }
1632         if (lock_taken)
1633                 MONO_SEM_POST (&tp->lock);
1634
1635         for (i = 0; i < MIN(njobs, tp->max_threads); i++)
1636                 pulse_on_new_job (tp);
1637 }
1638
1639 static void
1640 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
1641 {
1642         MonoMList *current;
1643         MonoArray *array;
1644         MonoObject *obj;
1645         int domain_count;
1646         int i;
1647
1648         domain_count = 0;
1649         MONO_SEM_WAIT (&tp->lock);
1650         current = tp->first;
1651         while (current) {
1652                 array = (MonoArray *) mono_mlist_get_data (current);
1653                 for (i = 0; i < QUEUE_LENGTH; i++) {
1654                         obj = mono_array_get (array, MonoObject*, i);
1655                         if (obj != NULL && obj->vtable->domain == domain) {
1656                                 domain_count++;
1657                                 mono_array_setref (array, i, NULL);
1658                                 threadpool_jobs_dec (obj);
1659                         }
1660                 }
1661                 current = mono_mlist_next (current);
1662         }
1663
1664         if (!domain_count) {
1665                 MONO_SEM_POST (&tp->lock);
1666                 return;
1667         }
1668
1669         current = tp->first;
1670         tp->first = NULL;
1671         tp->last = NULL;
1672         tp->head = 0;
1673         tp->tail = 0;
1674         MONO_SEM_POST (&tp->lock);
1675         /* Re-add everything but the nullified elements */
1676         while (current) {
1677                 array = (MonoArray *) mono_mlist_get_data (current);
1678                 threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
1679                 memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
1680                 current = mono_mlist_next (current);
1681         }
1682 }
1683
1684 /*
1685  * Clean up the threadpool of all domain jobs.
1686  * Can only be called as part of the domain unloading process as
1687  * it will wait for all jobs to be visible to the interruption code. 
1688  */
1689 gboolean
1690 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1691 {
1692         HANDLE sem_handle;
1693         int result = TRUE;
1694         guint32 start_time = 0;
1695
1696         g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1697
1698         threadpool_clear_queue (&async_tp, domain);
1699         threadpool_clear_queue (&async_io_tp, domain);
1700
1701         /*
1702          * There might be some threads out that could be about to execute stuff from the given domain.
1703          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1704          */
1705         sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1706
1707         domain->cleanup_semaphore = sem_handle;
1708         /*
1709          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1710          * and reading threadpool_jobs.
1711          * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1712          */
1713         mono_memory_write_barrier ();
1714
1715         if (domain->threadpool_jobs && timeout != -1)
1716                 start_time = mono_msec_ticks ();
1717         while (domain->threadpool_jobs) {
1718                 WaitForSingleObject (sem_handle, timeout);
1719                 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1720                         result = FALSE;
1721                         break;
1722                 }
1723         }
1724
1725         domain->cleanup_semaphore = NULL;
1726         CloseHandle (sem_handle);
1727         return result;
1728 }
1729
1730 static void
1731 threadpool_free_queue (ThreadPool *tp)
1732 {
1733         tp->head = tp->tail = 0;
1734         tp->first = NULL;
1735         tp->unused = NULL;
1736 }
1737
1738 gboolean
1739 mono_thread_pool_is_queue_array (MonoArray *o)
1740 {
1741         gpointer obj = o;
1742
1743         // FIXME: need some fix in sgen code.
1744         // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
1745         return obj == async_tp.first || obj == async_io_tp.first;
1746 }
1747
1748 static MonoWSQ *
1749 add_wsq (void)
1750 {
1751         int i;
1752         MonoWSQ *wsq;
1753
1754         EnterCriticalSection (&wsqs_lock);
1755         wsq = mono_wsq_create ();
1756         if (wsqs == NULL) {
1757                 LeaveCriticalSection (&wsqs_lock);
1758                 return NULL;
1759         }
1760         for (i = 0; i < wsqs->len; i++) {
1761                 if (g_ptr_array_index (wsqs, i) == NULL) {
1762                         wsqs->pdata [i] = wsq;
1763                         LeaveCriticalSection (&wsqs_lock);
1764                         return wsq;
1765                 }
1766         }
1767         g_ptr_array_add (wsqs, wsq);
1768         LeaveCriticalSection (&wsqs_lock);
1769         return wsq;
1770 }
1771
1772 static void
1773 remove_wsq (MonoWSQ *wsq)
1774 {
1775         gpointer data;
1776
1777         if (wsq == NULL)
1778                 return;
1779
1780         EnterCriticalSection (&wsqs_lock);
1781         if (wsqs == NULL) {
1782                 LeaveCriticalSection (&wsqs_lock);
1783                 return;
1784         }
1785         g_ptr_array_remove_fast (wsqs, wsq);
1786         data = NULL;
1787         while (mono_wsq_local_pop (&data)) {
1788                 threadpool_jobs_dec (data);
1789                 data = NULL;
1790         }
1791         mono_wsq_destroy (wsq);
1792         LeaveCriticalSection (&wsqs_lock);
1793 }
1794
1795 static void
1796 try_steal (gpointer *data, gboolean retry)
1797 {
1798         int i;
1799         int ms;
1800
1801         if (wsqs == NULL || data == NULL || *data != NULL)
1802                 return;
1803
1804         ms = 0;
1805         do {
1806                 if (mono_runtime_is_shutting_down ())
1807                         return;
1808                 for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
1809                         if (mono_runtime_is_shutting_down ()) {
1810                                 return;
1811                         }
1812                         mono_wsq_try_steal (wsqs->pdata [i], data, ms);
1813                         if (*data != NULL) {
1814                                 return;
1815                         }
1816                 }
1817                 ms += 10;
1818         } while (retry && ms < 11);
1819 }
1820
1821 static gboolean
1822 dequeue_or_steal (ThreadPool *tp, gpointer *data)
1823 {
1824         if (mono_runtime_is_shutting_down ())
1825                 return FALSE;
1826         TP_DEBUG ("Dequeue");
1827         MONO_SEM_WAIT (&tp->lock);
1828         *data = dequeue_job_nolock (tp);
1829         MONO_SEM_POST (&tp->lock);
1830         if (!tp->is_io && !*data)
1831                 try_steal (data, FALSE);
1832         return (*data != NULL);
1833 }
1834
1835 static void
1836 process_idle_times (ThreadPool *tp, gint64 t)
1837 {
1838         gint64 ticks;
1839         gint64 avg;
1840         gboolean compute_avg;
1841         gint new_threads;
1842         gint64 per1;
1843
1844         if (tp->ignore_times || t <= 0)
1845                 return;
1846
1847         compute_avg = FALSE;
1848         ticks = mono_100ns_ticks ();
1849         t = ticks - t;
1850         SPIN_LOCK (tp->sp_lock);
1851         if (tp->ignore_times) {
1852                 SPIN_UNLOCK (tp->sp_lock);
1853                 return;
1854         }
1855         tp->time_sum += t;
1856         tp->n_sum++;
1857         if (tp->last_check == 0)
1858                 tp->last_check = ticks;
1859         else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
1860                 tp->ignore_times = 1;
1861                 compute_avg = TRUE;
1862         }
1863         SPIN_UNLOCK (tp->sp_lock);
1864
1865         if (!compute_avg)
1866                 return;
1867
1868         //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
1869         tp->last_check = ticks;
1870         new_threads = 0;
1871         avg = tp->time_sum / tp->n_sum;
1872         if (tp->averages [1] == 0) {
1873                 tp->averages [1] = avg;
1874         } else {
1875                 per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
1876                 if (per1 > 5) {
1877                         if (avg > tp->averages [1]) {
1878                                 if (tp->averages [1] < tp->averages [0]) {
1879                                         new_threads = -1;
1880                                 } else {
1881                                         new_threads = 1;
1882                                 }
1883                         } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
1884                                 new_threads = 1;
1885                         }
1886                 } else {
1887                         int min, n;
1888                         min = tp->min_threads;
1889                         n = tp->nthreads;
1890                         if ((n - min) < min && tp->busy_threads == n)
1891                                 new_threads = 1;
1892                 }
1893                 /*
1894                 if (new_threads != 0) {
1895                         printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
1896                 }
1897                 */
1898         }
1899
1900         tp->time_sum = 0;
1901         tp->n_sum = 0;
1902
1903         tp->averages [0] = tp->averages [1];
1904         tp->averages [1] = avg;
1905         tp->ignore_times = 0;
1906
1907         if (new_threads == -1) {
1908                 if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
1909                         pulse_on_new_job (tp);
1910         }
1911 }
1912
1913 static gboolean
1914 should_i_die (ThreadPool *tp)
1915 {
1916         gboolean result = FALSE;
1917         if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
1918                 result = (tp->nthreads > tp->min_threads);
1919         return result;
1920 }
1921
1922 static void
1923 async_invoke_thread (gpointer data)
1924 {
1925         MonoDomain *domain;
1926         MonoInternalThread *thread;
1927         MonoWSQ *wsq;
1928         ThreadPool *tp;
1929         gboolean must_die;
1930   
1931         tp = data;
1932         wsq = NULL;
1933         if (!tp->is_io)
1934                 wsq = add_wsq ();
1935
1936         thread = mono_thread_internal_current ();
1937
1938         mono_profiler_thread_start (thread->tid);
1939         ves_icall_System_Threading_Thread_SetName_internal (thread, mono_string_new (mono_domain_get (), "Threapool worker"));
1940
1941         if (tp_start_func)
1942                 tp_start_func (tp_hooks_user_data);
1943
1944         data = NULL;
1945         for (;;) {
1946                 MonoAsyncResult *ar;
1947                 MonoClass *klass;
1948                 gboolean is_io_task;
1949                 gboolean is_socket;
1950                 int n_naps = 0;
1951
1952                 is_io_task = FALSE;
1953                 ar = (MonoAsyncResult *) data;
1954                 if (ar) {
1955                         InterlockedIncrement (&tp->busy_threads);
1956                         domain = ((MonoObject *)ar)->vtable->domain;
1957 #ifndef DISABLE_SOCKETS
1958                         klass = ((MonoObject *) data)->vtable->klass;
1959                         is_io_task = !is_corlib_asyncresult (domain, klass);
1960                         is_socket = FALSE;
1961                         if (is_io_task) {
1962                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
1963                                 is_socket = is_socketasyncresult (domain, klass);
1964                                 ar = state->ares;
1965                                 switch (state->operation) {
1966                                 case AIO_OP_RECEIVE:
1967                                         state->total = ICALL_RECV (state);
1968                                         break;
1969                                 case AIO_OP_SEND:
1970                                         state->total = ICALL_SEND (state);
1971                                         break;
1972                                 }
1973                         }
1974 #endif
1975                         /* worker threads invokes methods in different domains,
1976                          * so we need to set the right domain here */
1977                         g_assert (domain);
1978
1979                         if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
1980                                 threadpool_jobs_dec ((MonoObject *)ar);
1981                                 data = NULL;
1982                                 ar = NULL;
1983                                 InterlockedDecrement (&tp->busy_threads);
1984                         } else {
1985                                 mono_thread_push_appdomain_ref (domain);
1986                                 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1987                                         data = NULL;
1988                                         ar = NULL;
1989                                         mono_thread_pop_appdomain_ref ();
1990                                         InterlockedDecrement (&tp->busy_threads);
1991                                         continue;
1992                                 }
1993
1994                                 if (mono_domain_set (domain, FALSE)) {
1995                                         MonoObject *exc;
1996
1997                                         if (tp_item_begin_func)
1998                                                 tp_item_begin_func (tp_item_user_data);
1999
2000                                         if (!is_io_task && ar->add_time > 0)
2001                                                 process_idle_times (tp, ar->add_time);
2002                                         exc = mono_async_invoke (tp, ar);
2003                                         if (tp_item_end_func)
2004                                                 tp_item_end_func (tp_item_user_data);
2005                                         if (exc && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
2006                                                 gboolean unloaded;
2007                                                 MonoClass *klass;
2008
2009                                                 klass = exc->vtable->klass;
2010                                                 unloaded = is_appdomainunloaded_exception (exc->vtable->domain, klass);
2011                                                 if (!unloaded && klass != mono_defaults.threadabortexception_class) {
2012                                                         mono_unhandled_exception (exc);
2013                                                         exit (255);
2014                                                 }
2015                                         }
2016                                         if (is_socket && tp->is_io) {
2017                                                 MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
2018
2019                                                 if (state->completed && state->callback) {
2020                                                         MonoAsyncResult *cb_ares;
2021                                                         cb_ares = create_simple_asyncresult ((MonoObject *) state->callback,
2022                                                                                                 (MonoObject *) state);
2023                                                         icall_append_job ((MonoObject *) cb_ares);
2024                                                 }
2025                                         }
2026                                         mono_domain_set (mono_get_root_domain (), TRUE);
2027                                 }
2028                                 mono_thread_pop_appdomain_ref ();
2029                                 InterlockedDecrement (&tp->busy_threads);
2030                                 /* If the callee changes the background status, set it back to TRUE */
2031                                 mono_thread_clr_state (thread , ~ThreadState_Background);
2032                                 if (!mono_thread_test_state (thread , ThreadState_Background))
2033                                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
2034                         }
2035                 }
2036
2037                 ar = NULL;
2038                 data = NULL;
2039                 must_die = should_i_die (tp);
2040                 TP_DEBUG ("Trying to get a job");
2041                 if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
2042                         dequeue_or_steal (tp, &data);
2043                 TP_DEBUG ("Done trying to get a job %p", data);
2044
2045                 n_naps = 0;
2046                 while (!must_die && !data && n_naps < 4) {
2047                         gboolean res;
2048
2049                         TP_DEBUG ("Waiting");
2050                         InterlockedIncrement (&tp->waiting);
2051 #if defined(__OpenBSD__)
2052                         while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
2053 #else
2054                         while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
2055 #endif
2056                                 if (mono_runtime_is_shutting_down ())
2057                                         break;
2058                                 if (THREAD_WANTS_A_BREAK (thread))
2059                                         mono_thread_interruption_checkpoint ();
2060                         }
2061                         TP_DEBUG ("Done waiting");
2062                         InterlockedDecrement (&tp->waiting);
2063                         if (mono_runtime_is_shutting_down ())
2064                                 break;
2065                         must_die = should_i_die (tp);
2066                         dequeue_or_steal (tp, &data);
2067                         n_naps++;
2068                 }
2069
2070                 if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
2071                         mono_wsq_local_pop (&data);
2072                         if (data && must_die) {
2073                                 InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
2074                                 pulse_on_new_job (tp);
2075                         }
2076                 }
2077
2078                 if (!data) {
2079                         gint nt;
2080                         gboolean down;
2081                         while (1) {
2082                                 nt = tp->nthreads;
2083                                 down = mono_runtime_is_shutting_down ();
2084                                 if (!down && nt <= tp->min_threads)
2085                                         break;
2086                                 if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
2087                                         mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
2088                                         TP_DEBUG ("DIE");
2089                                         if (!tp->is_io) {
2090                                                 remove_wsq (wsq);
2091                                         }
2092
2093                                         mono_profiler_thread_end (thread->tid);
2094
2095                                         if (tp_finish_func)
2096                                                 tp_finish_func (tp_hooks_user_data);
2097                                         return;
2098                                 }
2099                         }
2100                 }
2101         }
2102
2103         g_assert_not_reached ();
2104 }
2105
2106 void
2107 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
2108 {
2109         *workerThreads = async_tp.max_threads - async_tp.busy_threads;
2110         *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
2111 }
2112
2113 void
2114 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
2115 {
2116         *workerThreads = async_tp.max_threads;
2117         *completionPortThreads = async_io_tp.max_threads;
2118 }
2119
2120 void
2121 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
2122 {
2123         *workerThreads = async_tp.min_threads;
2124         *completionPortThreads = async_io_tp.min_threads;
2125 }
2126
2127 MonoBoolean
2128 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
2129 {
2130         gint max_threads;
2131         gint max_io_threads;
2132
2133         max_threads = async_tp.max_threads;
2134         if (workerThreads <= 0 || workerThreads > max_threads)
2135                 return FALSE;
2136
2137         max_io_threads = async_io_tp.max_threads;
2138         if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
2139                 return FALSE;
2140
2141         InterlockedExchange (&async_tp.min_threads, workerThreads);
2142         InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
2143         if (workerThreads > async_tp.nthreads)
2144                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
2145         if (completionPortThreads > async_io_tp.nthreads)
2146                 mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
2147         return TRUE;
2148 }
2149
2150 MonoBoolean
2151 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
2152 {
2153         gint min_threads;
2154         gint min_io_threads;
2155         gint cpu_count;
2156
2157         cpu_count = mono_cpu_count ();
2158         min_threads = async_tp.min_threads;
2159         if (workerThreads < min_threads || workerThreads < cpu_count)
2160                 return FALSE;
2161
2162         /* We don't really have the concept of completion ports. Do we care here? */
2163         min_io_threads = async_io_tp.min_threads;
2164         if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
2165                 return FALSE;
2166
2167         InterlockedExchange (&async_tp.max_threads, workerThreads);
2168         InterlockedExchange (&async_io_tp.max_threads, completionPortThreads);
2169         return TRUE;
2170 }
2171
2172 /**
2173  * mono_install_threadpool_thread_hooks
2174  * @start_func: the function to be called right after a new threadpool thread is created. Can be NULL.
2175  * @finish_func: the function to be called right before a thredpool thread is exiting. Can be NULL.
2176  * @user_data: argument passed to @start_func and @finish_func.
2177  *
2178  * @start_fun will be called right after a threadpool thread is created and @finish_func right before a threadpool thread exits.
2179  * The calls will be made from the thread itself.
2180  */
2181 void
2182 mono_install_threadpool_thread_hooks (MonoThreadPoolFunc start_func, MonoThreadPoolFunc finish_func, gpointer user_data)
2183 {
2184         tp_start_func = start_func;
2185         tp_finish_func = finish_func;
2186         tp_hooks_user_data = user_data;
2187 }
2188
2189 /**
2190  * mono_install_threadpool_item_hooks
2191  * @begin_func: the function to be called before a threadpool work item processing starts.
2192  * @end_func: the function to be called after a threadpool work item is finished.
2193  * @user_data: argument passed to @begin_func and @end_func.
2194  *
2195  * The calls will be made from the thread itself and from the same AppDomain
2196  * where the work item was executed.
2197  *
2198  */
2199 void
2200 mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThreadPoolItemFunc end_func, gpointer user_data)
2201 {
2202         tp_item_begin_func = begin_func;
2203         tp_item_end_func = end_func;
2204         tp_item_user_data = user_data;
2205 }
2206