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