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