2008-10-03 Mark Probst <mark.probst@gmail.com>
[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  * (C) 2001-2003 Ximian, Inc.
9  * (c) 2004,2005 Novell, Inc. (http://www.novell.com)
10  */
11
12 #include <config.h>
13 #include <glib.h>
14
15 #define THREADS_PER_CPU 5 /* 20 + THREADS_PER_CPU * number of CPUs */
16
17 #include <mono/metadata/domain-internals.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/threads.h>
20 #include <mono/metadata/threads-types.h>
21 #include <mono/metadata/threadpool-internals.h>
22 #include <mono/metadata/exception.h>
23 #include <mono/metadata/file-io.h>
24 #include <mono/metadata/monitor.h>
25 #include <mono/metadata/mono-mlist.h>
26 #include <mono/metadata/marshal.h>
27 #include <mono/metadata/socket-io.h>
28 #include <mono/io-layer/io-layer.h>
29 #include <mono/metadata/gc-internal.h>
30 #include <mono/utils/mono-time.h>
31 #include <errno.h>
32 #ifdef HAVE_SYS_TIME_H
33 #include <sys/time.h>
34 #endif
35 #include <sys/types.h>
36 #include <fcntl.h>
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #include <string.h>
41
42 #include <mono/utils/mono-poll.h>
43 #ifdef HAVE_EPOLL
44 #include <sys/epoll.h>
45 #endif
46
47 #include "mono/io-layer/socket-wrappers.h"
48
49 #include "threadpool.h"
50
51 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
52                                                 ThreadState_SuspendRequested)) != 0)
53
54 #undef EPOLL_DEBUG
55
56 /* maximum number of worker threads */
57 static int mono_max_worker_threads;
58 static int mono_min_worker_threads;
59 static int mono_io_max_worker_threads;
60 static int mono_io_min_worker_threads;
61
62 /* current number of worker threads */
63 static int mono_worker_threads = 0;
64 static int io_worker_threads = 0;
65
66 /* current number of busy threads */
67 static int busy_worker_threads = 0;
68 static int busy_io_worker_threads;
69
70 /* mono_thread_pool_init called */
71 static int tp_inited;
72
73 /* we use this to store a reference to the AsyncResult to avoid GC */
74 static MonoGHashTable *ares_htable = NULL;
75
76 static CRITICAL_SECTION ares_lock;
77 static CRITICAL_SECTION io_queue_lock;
78 static int pending_io_items;
79
80 typedef struct {
81         CRITICAL_SECTION io_lock; /* access to sock_to_state */
82         int inited;
83         int pipe [2];
84         MonoGHashTable *sock_to_state;
85
86         HANDLE new_sem; /* access to newpfd and write side of the pipe */
87         mono_pollfd *newpfd;
88         gboolean epoll_disabled;
89 #ifdef HAVE_EPOLL
90         int epollfd;
91 #endif
92 } SocketIOData;
93
94 static SocketIOData socket_io_data;
95
96 /* we append a job */
97 static HANDLE job_added;
98 static HANDLE io_job_added;
99
100 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
101 typedef struct {
102         MonoObject         object;
103         MonoMethodMessage *msg;
104         MonoMethod        *cb_method;
105         MonoDelegate      *cb_target;
106         MonoObject        *state;
107         MonoObject        *res;
108         MonoArray         *out_args;
109         /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
110         guint64           wait_event;
111 } ASyncCall;
112
113 typedef struct {
114         MonoArray *array;
115         int first_elem;
116         int next_elem;
117 } TPQueue;
118
119 static void async_invoke_thread (gpointer data);
120 static void append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar);
121 static void start_thread_or_queue (MonoAsyncResult *ares);
122 static void mono_async_invoke (MonoAsyncResult *ares);
123 static MonoObject* dequeue_job (CRITICAL_SECTION *cs, TPQueue *list);
124 static void free_queue (TPQueue *list);
125
126 static TPQueue async_call_queue = {NULL, 0, 0};
127 static TPQueue async_io_queue = {NULL, 0, 0};
128
129 static MonoClass *async_call_klass;
130 static MonoClass *socket_async_call_klass;
131 static MonoClass *process_async_call_klass;
132
133 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
134 enum {
135         AIO_OP_FIRST,
136         AIO_OP_ACCEPT = 0,
137         AIO_OP_CONNECT,
138         AIO_OP_RECEIVE,
139         AIO_OP_RECEIVEFROM,
140         AIO_OP_SEND,
141         AIO_OP_SENDTO,
142         AIO_OP_RECV_JUST_CALLBACK,
143         AIO_OP_SEND_JUST_CALLBACK,
144         AIO_OP_READPIPE,
145         AIO_OP_LAST
146 };
147
148 static void
149 socket_io_cleanup (SocketIOData *data)
150 {
151         gint release;
152
153         if (data->inited == 0)
154                 return;
155
156         EnterCriticalSection (&data->io_lock);
157         data->inited = 0;
158 #ifdef PLATFORM_WIN32
159         closesocket (data->pipe [0]);
160         closesocket (data->pipe [1]);
161 #else
162         close (data->pipe [0]);
163         close (data->pipe [1]);
164 #endif
165         data->pipe [0] = -1;
166         data->pipe [1] = -1;
167         if (data->new_sem)
168                 CloseHandle (data->new_sem);
169         data->new_sem = NULL;
170         mono_g_hash_table_destroy (data->sock_to_state);
171         data->sock_to_state = NULL;
172         free_queue (&async_io_queue);
173         release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
174         if (io_job_added)
175                 ReleaseSemaphore (io_job_added, release, NULL);
176         g_free (data->newpfd);
177         data->newpfd = NULL;
178 #ifdef HAVE_EPOLL
179         if (FALSE == data->epoll_disabled)
180                 close (data->epollfd);
181 #endif
182         LeaveCriticalSection (&data->io_lock);
183 }
184
185 static int
186 get_event_from_state (MonoSocketAsyncResult *state)
187 {
188         switch (state->operation) {
189         case AIO_OP_ACCEPT:
190         case AIO_OP_RECEIVE:
191         case AIO_OP_RECV_JUST_CALLBACK:
192         case AIO_OP_RECEIVEFROM:
193         case AIO_OP_READPIPE:
194                 return MONO_POLLIN;
195         case AIO_OP_SEND:
196         case AIO_OP_SEND_JUST_CALLBACK:
197         case AIO_OP_SENDTO:
198         case AIO_OP_CONNECT:
199                 return MONO_POLLOUT;
200         default: /* Should never happen */
201                 g_print ("get_event_from_state: unknown value in switch!!!\n");
202                 return 0;
203         }
204 }
205
206 static int
207 get_events_from_list (MonoMList *list)
208 {
209         MonoSocketAsyncResult *state;
210         int events = 0;
211
212         while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
213                 events |= get_event_from_state (state);
214                 list = mono_mlist_next (list);
215         }
216
217         return events;
218 }
219
220 #define ICALL_RECV(x)   ves_icall_System_Net_Sockets_Socket_Receive_internal (\
221                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
222                                  x->socket_flags, &x->error);
223
224 #define ICALL_SEND(x)   ves_icall_System_Net_Sockets_Socket_Send_internal (\
225                                 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
226                                  x->socket_flags, &x->error);
227
228 static void
229 async_invoke_io_thread (gpointer data)
230 {
231         MonoDomain *domain;
232         MonoThread *thread;
233         thread = mono_thread_current ();
234         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
235
236         for (;;) {
237                 MonoSocketAsyncResult *state;
238                 MonoAsyncResult *ar;
239
240                 state = (MonoSocketAsyncResult *) data;
241                 if (state) {
242                         InterlockedDecrement (&pending_io_items);
243                         ar = state->ares;
244                         switch (state->operation) {
245                         case AIO_OP_RECEIVE:
246                                 state->total = ICALL_RECV (state);
247                                 break;
248                         case AIO_OP_SEND:
249                                 state->total = ICALL_SEND (state);
250                                 break;
251                         }
252
253                         /* worker threads invokes methods in different domains,
254                          * so we need to set the right domain here */
255                         domain = ((MonoObject *)ar)->vtable->domain;
256                         mono_thread_push_appdomain_ref (domain);
257                         if (mono_domain_set (domain, FALSE)) {
258                                 ASyncCall *ac;
259
260                                 mono_async_invoke (ar);
261                                 ac = (ASyncCall *) ar->object_data;
262                                 /*
263                                 if (ac->msg->exc != NULL)
264                                         mono_unhandled_exception (ac->msg->exc);
265                                 */
266                                 mono_domain_set (mono_get_root_domain (), TRUE);
267                         }
268                         mono_thread_pop_appdomain_ref ();
269                         InterlockedDecrement (&busy_io_worker_threads);
270                 }
271
272                 data = dequeue_job (&io_queue_lock, &async_io_queue);
273         
274                 if (!data) {
275                         guint32 wr;
276                         int timeout = 10000;
277                         guint32 start_time = mono_msec_ticks ();
278                         
279                         do {
280                                 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
281                                 if (THREAD_WANTS_A_BREAK (thread))
282                                         mono_thread_interruption_checkpoint ();
283                         
284                                 timeout -= mono_msec_ticks () - start_time;
285                         
286                                 if (wr != WAIT_TIMEOUT)
287                                         data = dequeue_job (&io_queue_lock, &async_io_queue);
288                         }
289                         while (!data && timeout > 0);
290                 }
291
292                 if (!data) {
293                         if (InterlockedDecrement (&io_worker_threads) < 2) {
294                                 /* If we have pending items, keep the thread alive */
295                                 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
296                                         InterlockedIncrement (&io_worker_threads);
297                                         continue;
298                                 }
299                         }
300                         return;
301                 }
302                 
303                 InterlockedIncrement (&busy_io_worker_threads);
304         }
305
306         g_assert_not_reached ();
307 }
308
309 static void
310 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
311 {
312         int busy, worker;
313         MonoDomain *domain;
314
315         busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
316         worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1); 
317         if (worker <= ++busy &&
318             worker < mono_io_max_worker_threads) {
319                 InterlockedIncrement (&busy_io_worker_threads);
320                 InterlockedIncrement (&io_worker_threads);
321                 domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
322                 mono_thread_create_internal (mono_get_root_domain (), async_invoke_io_thread, ares, TRUE);
323         } else {
324                 append_job (&io_queue_lock, &async_io_queue, (MonoObject*)ares);
325                 ReleaseSemaphore (io_job_added, 1, NULL);
326         }
327 }
328
329 static MonoMList *
330 process_io_event (MonoMList *list, int event)
331 {
332         MonoSocketAsyncResult *state;
333         MonoMList *oldlist;
334
335         oldlist = list;
336         state = NULL;
337         while (list) {
338                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
339                 if (get_event_from_state (state) == event)
340                         break;
341                 
342                 list = mono_mlist_next (list);
343         }
344
345         if (list != NULL) {
346                 oldlist = mono_mlist_remove_item (oldlist, list);
347 #ifdef EPOLL_DEBUG
348                 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
349 #endif
350                 InterlockedIncrement (&pending_io_items);
351                 start_io_thread_or_queue (state);
352         }
353
354         return oldlist;
355 }
356
357 static int
358 mark_bad_fds (mono_pollfd *pfds, int nfds)
359 {
360         int i, ret;
361         mono_pollfd *pfd;
362         int count = 0;
363
364         for (i = 0; i < nfds; i++) {
365                 pfd = &pfds [i];
366                 if (pfd->fd == -1)
367                         continue;
368
369                 ret = mono_poll (pfd, 1, 0);
370                 if (ret == -1 && errno == EBADF) {
371                         pfd->revents |= MONO_POLLNVAL;
372                         count++;
373                 } else if (ret == 1) {
374                         count++;
375                 }
376         }
377
378         return count;
379 }
380
381 static void
382 socket_io_poll_main (gpointer p)
383 {
384 #define INITIAL_POLLFD_SIZE     1024
385 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
386         SocketIOData *data = p;
387         mono_pollfd *pfds;
388         gint maxfd = 1;
389         gint allocated;
390         gint i;
391         MonoThread *thread;
392
393         thread = mono_thread_current ();
394         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
395
396         allocated = INITIAL_POLLFD_SIZE;
397         pfds = g_new0 (mono_pollfd, allocated);
398         INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
399         for (i = 1; i < allocated; i++)
400                 INIT_POLLFD (&pfds [i], -1, 0);
401
402         while (1) {
403                 int nsock = 0;
404                 mono_pollfd *pfd;
405                 char one [1];
406                 MonoMList *list;
407
408                 do {
409                         if (nsock == -1) {
410                                 if (THREAD_WANTS_A_BREAK (thread))
411                                         mono_thread_interruption_checkpoint ();
412                         }
413
414                         nsock = mono_poll (pfds, maxfd, -1);
415                 } while (nsock == -1 && errno == EINTR);
416
417                 /* 
418                  * Apart from EINTR, we only check EBADF, for the rest:
419                  *  EINVAL: mono_poll() 'protects' us from descriptor
420                  *      numbers above the limit if using select() by marking
421                  *      then as MONO_POLLERR.  If a system poll() is being
422                  *      used, the number of descriptor we're passing will not
423                  *      be over sysconf(_SC_OPEN_MAX), as the error would have
424                  *      happened when opening.
425                  *
426                  *  EFAULT: we own the memory pointed by pfds.
427                  *  ENOMEM: we're doomed anyway
428                  *
429                  */
430
431                 if (nsock == -1 && errno == EBADF) {
432                         pfds->revents = 0; /* Just in case... */
433                         nsock = mark_bad_fds (pfds, maxfd);
434                 }
435
436                 if ((pfds->revents & POLL_ERRORS) != 0) {
437                         /* We're supposed to die now, as the pipe has been closed */
438                         g_free (pfds);
439                         socket_io_cleanup (data);
440                         return;
441                 }
442
443                 /* Got a new socket */
444                 if ((pfds->revents & MONO_POLLIN) != 0) {
445                         int nread;
446
447                         for (i = 1; i < allocated; i++) {
448                                 pfd = &pfds [i];
449                                 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
450                                         break;
451                         }
452
453                         if (i == allocated) {
454                                 mono_pollfd *oldfd;
455
456                                 oldfd = pfds;
457                                 i = allocated;
458                                 allocated = allocated * 2;
459                                 pfds = g_renew (mono_pollfd, oldfd, allocated);
460                                 g_free (oldfd);
461                                 for (; i < allocated; i++)
462                                         INIT_POLLFD (&pfds [i], -1, 0);
463                         }
464 #ifndef PLATFORM_WIN32
465                         nread = read (data->pipe [0], one, 1);
466 #else
467                         nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
468 #endif
469                         if (nread <= 0) {
470                                 g_free (pfds);
471                                 return; /* we're closed */
472                         }
473
474                         INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
475                         ReleaseSemaphore (data->new_sem, 1, NULL);
476                         if (i >= maxfd)
477                                 maxfd = i + 1;
478                         nsock--;
479                 }
480
481                 if (nsock == 0)
482                         continue;
483
484                 EnterCriticalSection (&data->io_lock);
485                 if (data->inited == 0) {
486                         g_free (pfds);
487                         LeaveCriticalSection (&data->io_lock);
488                         return; /* cleanup called */
489                 }
490
491                 for (i = 1; i < maxfd && nsock > 0; i++) {
492                         pfd = &pfds [i];
493                         if (pfd->fd == -1 || pfd->revents == 0)
494                                 continue;
495
496                         nsock--;
497                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
498                         if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
499                                 list = process_io_event (list, MONO_POLLIN);
500                         }
501
502                         if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
503                                 list = process_io_event (list, MONO_POLLOUT);
504                         }
505
506                         if (list != NULL) {
507                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
508                                 pfd->events = get_events_from_list (list);
509                         } else {
510                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
511                                 pfd->fd = -1;
512                                 if (i == maxfd - 1)
513                                         maxfd--;
514                         }
515                 }
516                 LeaveCriticalSection (&data->io_lock);
517         }
518 }
519
520 #ifdef HAVE_EPOLL
521 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
522 static void
523 socket_io_epoll_main (gpointer p)
524 {
525         SocketIOData *data;
526         int epollfd;
527         MonoThread *thread;
528         struct epoll_event *events, *evt;
529         const int nevents = 512;
530         int ready = 0, i;
531
532         data = p;
533         epollfd = data->epollfd;
534         thread = mono_thread_current ();
535         thread->threadpool_thread = TRUE;
536         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
537         events = g_new0 (struct epoll_event, nevents);
538
539         while (1) {
540                 do {
541                         if (ready == -1) {
542                                 if (THREAD_WANTS_A_BREAK (thread))
543                                         mono_thread_interruption_checkpoint ();
544                         }
545 #ifdef EPOLL_DEBUG
546                         g_print ("epoll_wait init\n");
547 #endif
548                         ready = epoll_wait (epollfd, events, nevents, -1);
549 #ifdef EPOLL_DEBUG
550                         {
551                         int err = errno;
552                         g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
553                         errno = err;
554                         }
555 #endif
556                 } while (ready == -1 && errno == EINTR);
557
558                 if (ready == -1) {
559                         int err = errno;
560                         g_free (events);
561                         if (err != EBADF)
562                                 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
563
564                         close (epollfd);
565                         return;
566                 }
567
568                 EnterCriticalSection (&data->io_lock);
569                 if (data->inited == 0) {
570 #ifdef EPOLL_DEBUG
571                         g_print ("data->inited == 0\n");
572 #endif
573                         g_free (events);
574                         close (epollfd);
575                         return; /* cleanup called */
576                 }
577
578                 for (i = 0; i < ready; i++) {
579                         int fd;
580                         MonoMList *list;
581
582                         evt = &events [i];
583                         fd = evt->data.fd;
584                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
585 #ifdef EPOLL_DEBUG
586                         g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
587 #endif
588                         if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
589                                 list = process_io_event (list, MONO_POLLIN);
590                         }
591
592                         if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
593                                 list = process_io_event (list, MONO_POLLOUT);
594                         }
595
596                         if (list != NULL) {
597                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
598                                 evt->events = get_events_from_list (list);
599 #ifdef EPOLL_DEBUG
600                                 g_print ("MOD %d to %d\n", fd, evt->events);
601 #endif
602                                 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
603                                         if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
604 #ifdef EPOLL_DEBUG
605                                                 int err = errno;
606                                                 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
607                                                 errno = err;
608 #endif
609                                         }
610                                 }
611                         } else {
612                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
613 #ifdef EPOLL_DEBUG
614                                 g_print ("DEL %d\n", fd);
615 #endif
616                                 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
617                         }
618                 }
619                 LeaveCriticalSection (&data->io_lock);
620         }
621 }
622 #endif
623
624 /*
625  * select/poll wake up when a socket is closed, but epoll just removes
626  * the socket from its internal list without notification.
627  */
628 void
629 mono_thread_pool_remove_socket (int sock)
630 {
631         MonoMList *list, *next;
632         MonoSocketAsyncResult *state;
633
634         if (socket_io_data.inited == FALSE)
635                 return;
636
637         EnterCriticalSection (&socket_io_data.io_lock);
638         list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
639         if (list) {
640                 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
641         }
642         LeaveCriticalSection (&socket_io_data.io_lock);
643         
644         while (list) {
645                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
646                 if (state->operation == AIO_OP_RECEIVE)
647                         state->operation = AIO_OP_RECV_JUST_CALLBACK;
648                 else if (state->operation == AIO_OP_SEND)
649                         state->operation = AIO_OP_SEND_JUST_CALLBACK;
650
651                 next = mono_mlist_remove_item (list, list);
652                 list = process_io_event (list, MONO_POLLIN);
653                 if (list)
654                         process_io_event (list, MONO_POLLOUT);
655
656                 list = next;
657         }
658 }
659
660 #ifdef PLATFORM_WIN32
661 static void
662 connect_hack (gpointer x)
663 {
664         struct sockaddr_in *addr = (struct sockaddr_in *) x;
665         int count = 0;
666
667         while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
668                 Sleep (500);
669                 if (++count > 3) {
670                         g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
671                         g_assert (WSAGetLastError ());
672                 }
673         }
674 }
675 #endif
676
677 static void
678 socket_io_init (SocketIOData *data)
679 {
680 #ifdef PLATFORM_WIN32
681         struct sockaddr_in server;
682         struct sockaddr_in client;
683         SOCKET srv;
684         int len;
685 #endif
686         int inited;
687
688         inited = InterlockedCompareExchange (&data->inited, -1, -1);
689         if (inited == 1)
690                 return;
691
692         EnterCriticalSection (&data->io_lock);
693         inited = InterlockedCompareExchange (&data->inited, -1, -1);
694         if (inited == 1) {
695                 LeaveCriticalSection (&data->io_lock);
696                 return;
697         }
698
699 #ifdef HAVE_EPOLL
700         data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
701         if (FALSE == data->epoll_disabled) {
702                 data->epollfd = epoll_create (256);
703                 data->epoll_disabled = (data->epollfd == -1);
704                 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
705                         g_message ("epoll_create() failed. Using plain poll().");
706         } else {
707                 data->epollfd = -1;
708         }
709 #else
710         data->epoll_disabled = TRUE;
711 #endif
712
713 #ifndef PLATFORM_WIN32
714         if (data->epoll_disabled) {
715                 if (pipe (data->pipe) != 0) {
716                         int err = errno;
717                         perror ("mono");
718                         g_assert (err);
719                 }
720         } else {
721                 data->pipe [0] = -1;
722                 data->pipe [1] = -1;
723         }
724 #else
725         srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
726         g_assert (srv != INVALID_SOCKET);
727         data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
728         g_assert (data->pipe [1] != INVALID_SOCKET);
729
730         server.sin_family = AF_INET;
731         server.sin_addr.s_addr = inet_addr ("127.0.0.1");
732         server.sin_port = 0;
733         if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
734                 g_print ("%d\n", WSAGetLastError ());
735                 g_assert (1 != 0);
736         }
737
738         len = sizeof (server);
739         getsockname (srv, (SOCKADDR *) &server, &len);
740         listen (srv, 1);
741         mono_thread_create (mono_get_root_domain (), connect_hack, &server);
742         len = sizeof (server);
743         data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
744         g_assert (data->pipe [0] != INVALID_SOCKET);
745         closesocket (srv);
746 #endif
747         mono_io_max_worker_threads = mono_max_worker_threads / 2;
748         if (mono_io_max_worker_threads < 10)
749                 mono_io_max_worker_threads = 10;
750
751         data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
752
753         if (data->epoll_disabled) {
754                 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
755                 g_assert (data->new_sem != NULL);
756         }
757         io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
758         g_assert (io_job_added != NULL);
759         InitializeCriticalSection (&io_queue_lock);
760         if (data->epoll_disabled) {
761                 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
762         }
763 #ifdef HAVE_EPOLL
764         else {
765                 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
766         }
767 #endif
768         InterlockedCompareExchange (&data->inited, 1, 0);
769         LeaveCriticalSection (&data->io_lock);
770 }
771
772 static void
773 socket_io_add_poll (MonoSocketAsyncResult *state)
774 {
775         int events;
776         char msg [1];
777         MonoMList *list;
778         SocketIOData *data = &socket_io_data;
779
780 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
781         /* select() for connect() does not work well on the Mac. Bug #75436. */
782         /* Bug #77637 for the BSD 6 case */
783         /* Bug #78888 for the Windows case */
784         if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
785                 start_io_thread_or_queue (state);
786                 return;
787         }
788 #endif
789         WaitForSingleObject (data->new_sem, INFINITE);
790         if (data->newpfd == NULL)
791                 data->newpfd = g_new0 (mono_pollfd, 1);
792
793         EnterCriticalSection (&data->io_lock);
794         /* FIXME: 64 bit issue: handle can be a pointer on windows? */
795         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
796         if (list == NULL) {
797                 list = mono_mlist_alloc ((MonoObject*)state);
798         } else {
799                 list = mono_mlist_append (list, (MonoObject*)state);
800         }
801
802         events = get_events_from_list (list);
803         INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
804         mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
805         LeaveCriticalSection (&data->io_lock);
806         *msg = (char) state->operation;
807 #ifndef PLATFORM_WIN32
808         write (data->pipe [1], msg, 1);
809 #else
810         send ((SOCKET) data->pipe [1], msg, 1, 0);
811 #endif
812 }
813
814 #ifdef HAVE_EPOLL
815 static gboolean
816 socket_io_add_epoll (MonoSocketAsyncResult *state)
817 {
818         MonoMList *list;
819         SocketIOData *data = &socket_io_data;
820         struct epoll_event event;
821         int epoll_op, ievt;
822         int fd;
823
824         memset (&event, 0, sizeof (struct epoll_event));
825         fd = GPOINTER_TO_INT (state->handle);
826         EnterCriticalSection (&data->io_lock);
827         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
828         if (list == NULL) {
829                 list = mono_mlist_alloc ((MonoObject*)state);
830                 epoll_op = EPOLL_CTL_ADD;
831         } else {
832                 list = mono_mlist_append (list, (MonoObject*)state);
833                 epoll_op = EPOLL_CTL_MOD;
834         }
835
836         ievt = get_events_from_list (list);
837         if ((ievt & MONO_POLLIN) != 0)
838                 event.events |= EPOLLIN;
839         if ((ievt & MONO_POLLOUT) != 0)
840                 event.events |= EPOLLOUT;
841
842         mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
843         event.data.fd = fd;
844 #ifdef EPOLL_DEBUG
845         g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
846 #endif
847         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
848                 int err = errno;
849                 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
850                         epoll_op = EPOLL_CTL_MOD;
851                         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
852                                 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
853                         }
854                 }
855         }
856
857         LeaveCriticalSection (&data->io_lock);
858         return TRUE;
859 }
860 #endif
861
862 static void
863 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
864 {
865         socket_io_init (&socket_io_data);
866         MONO_OBJECT_SETREF (state, ares, ares);
867 #ifdef HAVE_EPOLL
868         if (socket_io_data.epoll_disabled == FALSE) {
869                 if (socket_io_add_epoll (state))
870                         return;
871         }
872 #endif
873         socket_io_add_poll (state);
874 }
875
876 static gboolean
877 socket_io_filter (MonoObject *target, MonoObject *state)
878 {
879         gint op;
880         MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
881         MonoClass *klass;
882
883         if (target == NULL || state == NULL)
884                 return FALSE;
885
886         if (socket_async_call_klass == NULL) {
887                 klass = target->vtable->klass;
888                 /* Check if it's SocketAsyncCall in System.Net.Sockets
889                  * FIXME: check the assembly is signed correctly for extra care
890                  */
891                 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0 
892                                 && strcmp (mono_image_get_name (klass->image), "System") == 0
893                                 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
894                         socket_async_call_klass = klass;
895         }
896
897         if (process_async_call_klass == NULL) {
898                 klass = target->vtable->klass;
899                 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
900                  * FIXME: check the assembly is signed correctly for extra care
901                  */
902                 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0 
903                                 && strcmp (mono_image_get_name (klass->image), "System") == 0
904                                 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
905                         process_async_call_klass = klass;
906         }
907         /* return both when socket_async_call_klass has not been seen yet and when
908          * the object is not an instance of the class.
909          */
910         if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
911                 return FALSE;
912
913         op = sock_res->operation;
914         if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
915                 return FALSE;
916
917         return TRUE;
918 }
919
920 static void
921 mono_async_invoke (MonoAsyncResult *ares)
922 {
923         ASyncCall *ac = (ASyncCall *)ares->object_data;
924         MonoThread *thread = NULL;
925         MonoObject *res, *exc = NULL;
926         MonoArray *out_args = NULL;
927
928         if (ares->execution_context) {
929                 /* use captured ExecutionContext (if available) */
930                 thread = mono_thread_current ();
931                 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
932                 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
933         } else {
934                 ares->original_context = NULL;
935         }
936
937         ac->msg->exc = NULL;
938         res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
939         MONO_OBJECT_SETREF (ac, res, res);
940         MONO_OBJECT_SETREF (ac, msg->exc, exc);
941         MONO_OBJECT_SETREF (ac, out_args, out_args);
942
943         ares->completed = 1;
944
945         /* call async callback if cb_method != null*/
946         if (ac->cb_method) {
947                 MonoObject *exc = NULL;
948                 void *pa = &ares;
949                 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
950                 /* 'exc' will be the previous ac->msg->exc if not NULL and not
951                  * catched. If catched, this will be set to NULL and the
952                  * exception will not be printed. */
953                 MONO_OBJECT_SETREF (ac->msg, exc, exc);
954         }
955
956         /* restore original thread execution context if flow isn't suppressed, i.e. non null */
957         if (ares->original_context) {
958                 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
959                 ares->original_context = NULL;
960         }
961
962         /* notify listeners */
963         mono_monitor_enter ((MonoObject *) ares);
964         if (ares->handle != NULL) {
965                 ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
966                 SetEvent ((gpointer)(gsize)ac->wait_event);
967         }
968         mono_monitor_exit ((MonoObject *) ares);
969
970         EnterCriticalSection (&ares_lock);
971         mono_g_hash_table_remove (ares_htable, ares);
972         LeaveCriticalSection (&ares_lock);
973 }
974
975 void
976 mono_thread_pool_init ()
977 {
978         SYSTEM_INFO info;
979         int threads_per_cpu = THREADS_PER_CPU;
980
981         if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
982                 return;
983
984         MONO_GC_REGISTER_ROOT (ares_htable);
985         MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
986         InitializeCriticalSection (&socket_io_data.io_lock);
987         InitializeCriticalSection (&ares_lock);
988         ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
989         job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
990         g_assert (job_added != NULL);
991         GetSystemInfo (&info);
992         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
993                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
994                 if (threads_per_cpu <= 0)
995                         threads_per_cpu = THREADS_PER_CPU;
996         }
997
998         mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
999
1000         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1001         g_assert (async_call_klass);
1002 }
1003
1004 MonoAsyncResult *
1005 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1006                       MonoObject *state)
1007 {
1008         MonoDomain *domain = mono_domain_get ();
1009         MonoAsyncResult *ares;
1010         ASyncCall *ac;
1011
1012         ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1013         MONO_OBJECT_SETREF (ac, msg, msg);
1014         MONO_OBJECT_SETREF (ac, state, state);
1015
1016         if (async_callback) {
1017                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1018                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1019         }
1020
1021         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1022         MONO_OBJECT_SETREF (ares, async_delegate, target);
1023
1024         EnterCriticalSection (&ares_lock);
1025         mono_g_hash_table_insert (ares_htable, ares, ares);
1026         LeaveCriticalSection (&ares_lock);
1027
1028         if (socket_io_filter (target, state)) {
1029                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1030                 return ares;
1031         }
1032
1033         start_thread_or_queue (ares);
1034         return ares;
1035 }
1036
1037 static void
1038 start_thread_or_queue (MonoAsyncResult *ares)
1039 {
1040         int busy, worker;
1041
1042         busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1043         worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1044         if (worker <= ++busy &&
1045             worker < mono_max_worker_threads) {
1046                 InterlockedIncrement (&mono_worker_threads);
1047                 InterlockedIncrement (&busy_worker_threads);
1048                 mono_thread_create_internal (mono_get_root_domain (), async_invoke_thread, ares, TRUE);
1049         } else {
1050                 append_job (&mono_delegate_section, &async_call_queue, (MonoObject*)ares);
1051                 ReleaseSemaphore (job_added, 1, NULL);
1052         }
1053 }
1054
1055 MonoObject *
1056 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1057 {
1058         ASyncCall *ac;
1059
1060         *exc = NULL;
1061         *out_args = NULL;
1062
1063         /* check if already finished */
1064         mono_monitor_enter ((MonoObject *) ares);
1065         
1066         if (ares->endinvoke_called) {
1067                 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System", 
1068                                               "InvalidOperationException");
1069                 mono_monitor_exit ((MonoObject *) ares);
1070                 return NULL;
1071         }
1072
1073         ares->endinvoke_called = 1;
1074         ac = (ASyncCall *)ares->object_data;
1075
1076         g_assert (ac != NULL);
1077
1078         /* wait until we are really finished */
1079         if (!ares->completed) {
1080                 if (ares->handle == NULL) {
1081                         ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1082                         g_assert(ac->wait_event != 0);
1083                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1084                 }
1085                 mono_monitor_exit ((MonoObject *) ares);
1086                 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1087         } else {
1088                 mono_monitor_exit ((MonoObject *) ares);
1089         }
1090
1091         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1092         *out_args = ac->out_args;
1093
1094         return ac->res;
1095 }
1096
1097 void
1098 mono_thread_pool_cleanup (void)
1099 {
1100         gint release;
1101
1102         EnterCriticalSection (&mono_delegate_section);
1103         free_queue (&async_call_queue);
1104         release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1105         LeaveCriticalSection (&mono_delegate_section);
1106         if (job_added)
1107                 ReleaseSemaphore (job_added, release, NULL);
1108
1109         socket_io_cleanup (&socket_io_data);
1110 }
1111
1112 static void
1113 append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar)
1114 {
1115         EnterCriticalSection (cs);
1116         if (list->array && (list->next_elem < mono_array_length (list->array))) {
1117                 mono_array_setref (list->array, list->next_elem, ar);
1118                 list->next_elem++;
1119                 LeaveCriticalSection (cs);
1120                 return;
1121         }
1122         if (!list->array) {
1123                 MONO_GC_REGISTER_ROOT (list->array);
1124                 list->array = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, 16);
1125         } else {
1126                 int count = list->next_elem - list->first_elem;
1127                 /* slide the array or create a larger one if it's full */
1128                 if (list->first_elem) {
1129                         mono_array_memcpy_refs (list->array, 0, list->array, list->first_elem, count);
1130                 } else {
1131                         MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) * 2);
1132                         mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1133                         list->array = newa;
1134                 }
1135                 list->first_elem = 0;
1136                 list->next_elem = count;
1137         }
1138         mono_array_setref (list->array, list->next_elem, ar);
1139         list->next_elem++;
1140         LeaveCriticalSection (cs);
1141 }
1142
1143 static MonoObject*
1144 dequeue_job (CRITICAL_SECTION *cs, TPQueue *list)
1145 {
1146         MonoObject *ar;
1147         int count;
1148
1149         EnterCriticalSection (cs);
1150         if (!list->array || list->first_elem == list->next_elem) {
1151                 LeaveCriticalSection (cs);
1152                 return NULL;
1153         }
1154         ar = mono_array_get (list->array, MonoObject*, list->first_elem);
1155         list->first_elem++;
1156         count = list->next_elem - list->first_elem;
1157         /* reduce the size of the array if it's mostly empty */
1158         if (mono_array_length (list->array) > 16 && count < (mono_array_length (list->array) / 3)) {
1159                 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) / 2);
1160                 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1161                 list->array = newa;
1162                 list->first_elem = 0;
1163                 list->next_elem = count;
1164         }
1165         LeaveCriticalSection (cs);
1166
1167         return ar;
1168 }
1169
1170 static void
1171 free_queue (TPQueue *list)
1172 {
1173         list->array = NULL;
1174         list->first_elem = list->next_elem = 0;
1175 }
1176
1177 static void
1178 async_invoke_thread (gpointer data)
1179 {
1180         MonoDomain *domain;
1181         MonoThread *thread;
1182         int workers, min;
1183  
1184         thread = mono_thread_current ();
1185         thread->threadpool_thread = TRUE;
1186         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1187
1188         for (;;) {
1189                 MonoAsyncResult *ar;
1190
1191                 ar = (MonoAsyncResult *) data;
1192                 if (ar) {
1193                         /* worker threads invokes methods in different domains,
1194                          * so we need to set the right domain here */
1195                         domain = ((MonoObject *)ar)->vtable->domain;
1196                         mono_thread_push_appdomain_ref (domain);
1197                         if (mono_domain_set (domain, FALSE)) {
1198                                 ASyncCall *ac;
1199
1200                                 mono_async_invoke (ar);
1201                                 ac = (ASyncCall *) ar->object_data;
1202                                 /*
1203                                 if (ac->msg->exc != NULL)
1204                                         mono_unhandled_exception (ac->msg->exc);
1205                                 */
1206                                 mono_domain_set (mono_get_root_domain (), TRUE);
1207                         }
1208                         mono_thread_pop_appdomain_ref ();
1209                         InterlockedDecrement (&busy_worker_threads);
1210                 }
1211
1212                 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1213
1214                 if (!data) {
1215                         guint32 wr;
1216                         int timeout = 10000;
1217                         guint32 start_time = mono_msec_ticks ();
1218                         
1219                         do {
1220                                 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1221                                 if (THREAD_WANTS_A_BREAK (thread))
1222                                         mono_thread_interruption_checkpoint ();
1223                         
1224                                 timeout -= mono_msec_ticks () - start_time;
1225                         
1226                                 if (wr != WAIT_TIMEOUT)
1227                                         data = dequeue_job (&mono_delegate_section, &async_call_queue);
1228                         }
1229                         while (!data && timeout > 0);
1230                 }
1231
1232                 if (!data) {
1233                         workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1234                         min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1); 
1235         
1236                         while (!data && workers <= min) {
1237                                 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1238                                 if (THREAD_WANTS_A_BREAK (thread))
1239                                         mono_thread_interruption_checkpoint ();
1240                         
1241                                 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1242                                 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1243                                 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1); 
1244                         }
1245                 }
1246         
1247                 if (!data) {
1248                         InterlockedDecrement (&mono_worker_threads);
1249                         return;
1250                 }
1251                 
1252                 InterlockedIncrement (&busy_worker_threads);
1253         }
1254
1255         g_assert_not_reached ();
1256 }
1257
1258 void
1259 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1260 {
1261         gint busy, busy_io;
1262
1263         MONO_ARCH_SAVE_REGS;
1264
1265         busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1266         busy_io = (gint) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
1267         *workerThreads = mono_max_worker_threads - busy;
1268         *completionPortThreads = mono_io_max_worker_threads - busy_io;
1269 }
1270
1271 void
1272 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1273 {
1274         MONO_ARCH_SAVE_REGS;
1275
1276         *workerThreads = mono_max_worker_threads;
1277         *completionPortThreads = mono_io_max_worker_threads;
1278 }
1279
1280 void
1281 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1282 {
1283         gint workers, workers_io;
1284
1285         MONO_ARCH_SAVE_REGS;
1286
1287         workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1288         workers_io = (gint) InterlockedCompareExchange (&mono_io_min_worker_threads, 0, -1);
1289
1290         *workerThreads = workers;
1291         *completionPortThreads = workers_io;
1292 }
1293
1294 MonoBoolean
1295 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1296 {
1297         MONO_ARCH_SAVE_REGS;
1298
1299         if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1300                 return FALSE;
1301
1302         if (completionPortThreads < 0 || completionPortThreads > mono_io_max_worker_threads)
1303                 return FALSE;
1304
1305         InterlockedExchange (&mono_min_worker_threads, workerThreads);
1306         InterlockedExchange (&mono_io_min_worker_threads, completionPortThreads);
1307         /* FIXME: should actually start the idle threads if needed */
1308         return TRUE;
1309 }
1310
1311 MonoBoolean
1312 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1313 {
1314         MONO_ARCH_SAVE_REGS;
1315
1316         if (workerThreads < mono_max_worker_threads)
1317                 return FALSE;
1318
1319         if (completionPortThreads < mono_io_max_worker_threads)
1320                 return FALSE;
1321
1322         InterlockedExchange (&mono_max_worker_threads, workerThreads);
1323         InterlockedExchange (&mono_io_max_worker_threads, completionPortThreads);
1324         return TRUE;
1325 }