2007-09-25 Rodrigo Kumpera <rkumpera@novell.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/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         thread->threadpool_thread = TRUE;
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 = GetTickCount ();
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 -= GetTickCount () - 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 (mono_get_root_domain (), async_invoke_io_thread, ares);
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         thread->threadpool_thread = TRUE;
400         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
401
402         allocated = INITIAL_POLLFD_SIZE;
403         pfds = g_new0 (mono_pollfd, allocated);
404         INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
405         for (i = 1; i < allocated; i++)
406                 INIT_POLLFD (&pfds [i], -1, 0);
407
408         while (1) {
409                 int nsock = 0;
410                 mono_pollfd *pfd;
411                 char one [1];
412                 MonoMList *list;
413
414                 do {
415                         if (nsock == -1) {
416                                 if (THREAD_WANTS_A_BREAK (thread))
417                                         mono_thread_interruption_checkpoint ();
418                         }
419
420                         nsock = mono_poll (pfds, maxfd, -1);
421                 } while (nsock == -1 && errno == EINTR);
422
423                 /* 
424                  * Apart from EINTR, we only check EBADF, for the rest:
425                  *  EINVAL: mono_poll() 'protects' us from descriptor
426                  *      numbers above the limit if using select() by marking
427                  *      then as MONO_POLLERR.  If a system poll() is being
428                  *      used, the number of descriptor we're passing will not
429                  *      be over sysconf(_SC_OPEN_MAX), as the error would have
430                  *      happened when opening.
431                  *
432                  *  EFAULT: we own the memory pointed by pfds.
433                  *  ENOMEM: we're doomed anyway
434                  *
435                  */
436
437                 if (nsock == -1 && errno == EBADF) {
438                         pfds->revents = 0; /* Just in case... */
439                         nsock = mark_bad_fds (pfds, maxfd);
440                 }
441
442                 if ((pfds->revents & POLL_ERRORS) != 0) {
443                         /* We're supposed to die now, as the pipe has been closed */
444                         g_free (pfds);
445                         socket_io_cleanup (data);
446                         return;
447                 }
448
449                 /* Got a new socket */
450                 if ((pfds->revents & MONO_POLLIN) != 0) {
451                         int nread;
452
453                         for (i = 1; i < allocated; i++) {
454                                 pfd = &pfds [i];
455                                 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
456                                         break;
457                         }
458
459                         if (i == allocated) {
460                                 mono_pollfd *oldfd;
461
462                                 oldfd = pfds;
463                                 i = allocated;
464                                 allocated = allocated * 2;
465                                 pfds = g_renew (mono_pollfd, oldfd, allocated);
466                                 g_free (oldfd);
467                                 for (; i < allocated; i++)
468                                         INIT_POLLFD (&pfds [i], -1, 0);
469                         }
470 #ifndef PLATFORM_WIN32
471                         nread = read (data->pipe [0], one, 1);
472 #else
473                         nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
474 #endif
475                         if (nread <= 0) {
476                                 g_free (pfds);
477                                 return; /* we're closed */
478                         }
479
480                         INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
481                         ReleaseSemaphore (data->new_sem, 1, NULL);
482                         if (i >= maxfd)
483                                 maxfd = i + 1;
484                         nsock--;
485                 }
486
487                 if (nsock == 0)
488                         continue;
489
490                 EnterCriticalSection (&data->io_lock);
491                 if (data->inited == 0) {
492                         g_free (pfds);
493                         LeaveCriticalSection (&data->io_lock);
494                         return; /* cleanup called */
495                 }
496
497                 for (i = 1; i < maxfd && nsock > 0; i++) {
498                         pfd = &pfds [i];
499                         if (pfd->fd == -1 || pfd->revents == 0)
500                                 continue;
501
502                         nsock--;
503                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
504                         if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
505                                 list = process_io_event (list, MONO_POLLIN);
506                         }
507
508                         if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
509                                 list = process_io_event (list, MONO_POLLOUT);
510                         }
511
512                         if (list != NULL) {
513                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
514                                 pfd->events = get_events_from_list (list);
515                         } else {
516                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
517                                 pfd->fd = -1;
518                                 if (i == maxfd - 1)
519                                         maxfd--;
520                         }
521                 }
522                 LeaveCriticalSection (&data->io_lock);
523         }
524 }
525
526 #ifdef HAVE_EPOLL
527 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
528 static void
529 socket_io_epoll_main (gpointer p)
530 {
531         SocketIOData *data;
532         int epollfd;
533         MonoThread *thread;
534         struct epoll_event *events, *evt;
535         const int nevents = 512;
536         int ready = 0, i;
537
538         data = p;
539         epollfd = data->epollfd;
540         thread = mono_thread_current ();
541         thread->threadpool_thread = TRUE;
542         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
543         events = g_new0 (struct epoll_event, nevents);
544
545         while (1) {
546                 do {
547                         if (ready == -1) {
548                                 if (THREAD_WANTS_A_BREAK (thread))
549                                         mono_thread_interruption_checkpoint ();
550                         }
551 #ifdef EPOLL_DEBUG
552                         g_print ("epoll_wait init\n");
553 #endif
554                         ready = epoll_wait (epollfd, events, nevents, -1);
555 #ifdef EPOLL_DEBUG
556                         {
557                         int err = errno;
558                         g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
559                         errno = err;
560                         }
561 #endif
562                 } while (ready == -1 && errno == EINTR);
563
564                 if (ready == -1) {
565                         int err = errno;
566                         g_free (events);
567                         if (err != EBADF)
568                                 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
569
570                         close (epollfd);
571                         return;
572                 }
573
574                 EnterCriticalSection (&data->io_lock);
575                 if (data->inited == 0) {
576 #ifdef EPOLL_DEBUG
577                         g_print ("data->inited == 0\n");
578 #endif
579                         g_free (events);
580                         close (epollfd);
581                         return; /* cleanup called */
582                 }
583
584                 for (i = 0; i < ready; i++) {
585                         int fd;
586                         MonoMList *list;
587
588                         evt = &events [i];
589                         fd = evt->data.fd;
590                         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
591 #ifdef EPOLL_DEBUG
592                         g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
593 #endif
594                         if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
595                                 list = process_io_event (list, MONO_POLLIN);
596                         }
597
598                         if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
599                                 list = process_io_event (list, MONO_POLLOUT);
600                         }
601
602                         if (list != NULL) {
603                                 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
604                                 evt->events = get_events_from_list (list);
605 #ifdef EPOLL_DEBUG
606                                 g_print ("MOD %d to %d\n", fd, evt->events);
607 #endif
608                                 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
609                                         if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
610 #ifdef EPOLL_DEBUG
611                                                 int err = errno;
612                                                 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
613                                                 errno = err;
614 #endif
615                                         }
616                                 }
617                         } else {
618                                 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
619 #ifdef EPOLL_DEBUG
620                                 g_print ("DEL %d\n", fd);
621 #endif
622                                 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
623                         }
624                 }
625                 LeaveCriticalSection (&data->io_lock);
626         }
627 }
628 #endif
629
630 /*
631  * select/poll wake up when a socket is closed, but epoll just removes
632  * the socket from its internal list without notification.
633  */
634 void
635 mono_thread_pool_remove_socket (int sock)
636 {
637 #ifdef HAVE_EPOLL
638         MonoMList *list, *next;
639         MonoSocketAsyncResult *state;
640
641         if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
642                 return;
643
644         EnterCriticalSection (&socket_io_data.io_lock);
645         list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
646         if (list) {
647                 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
648         }
649         LeaveCriticalSection (&socket_io_data.io_lock);
650         
651         while (list) {
652                 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
653                 if (state->operation == AIO_OP_RECEIVE)
654                         state->operation = AIO_OP_RECV_JUST_CALLBACK;
655                 else if (state->operation == AIO_OP_SEND)
656                         state->operation = AIO_OP_SEND_JUST_CALLBACK;
657
658                 next = mono_mlist_remove_item (list, list);
659                 list = process_io_event (list, MONO_POLLIN);
660                 if (list)
661                         process_io_event (list, MONO_POLLOUT);
662
663                 list = next;
664         }
665 #endif
666 }
667
668 #ifdef PLATFORM_WIN32
669 static void
670 connect_hack (gpointer x)
671 {
672         struct sockaddr_in *addr = (struct sockaddr_in *) x;
673         int count = 0;
674
675         while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
676                 Sleep (500);
677                 if (++count > 3) {
678                         g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
679                         g_assert (WSAGetLastError ());
680                 }
681         }
682 }
683 #endif
684
685 static void
686 socket_io_init (SocketIOData *data)
687 {
688 #ifdef PLATFORM_WIN32
689         struct sockaddr_in server;
690         struct sockaddr_in client;
691         SOCKET srv;
692         int len;
693 #endif
694         int inited;
695
696         inited = InterlockedCompareExchange (&data->inited, -1, -1);
697         if (inited == 1)
698                 return;
699
700         EnterCriticalSection (&data->io_lock);
701         inited = InterlockedCompareExchange (&data->inited, -1, -1);
702         if (inited == 1) {
703                 LeaveCriticalSection (&data->io_lock);
704                 return;
705         }
706
707 #ifdef HAVE_EPOLL
708         data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
709         if (FALSE == data->epoll_disabled) {
710                 data->epollfd = epoll_create (256);
711                 data->epoll_disabled = (data->epollfd == -1);
712                 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
713                         g_message ("epoll_create() failed. Using plain poll().");
714         } else {
715                 data->epollfd = -1;
716         }
717 #else
718         data->epoll_disabled = TRUE;
719 #endif
720
721 #ifndef PLATFORM_WIN32
722         if (data->epoll_disabled) {
723                 if (pipe (data->pipe) != 0) {
724                         int err = errno;
725                         perror ("mono");
726                         g_assert (err);
727                 }
728         } else {
729                 data->pipe [0] = -1;
730                 data->pipe [1] = -1;
731         }
732 #else
733         srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
734         g_assert (srv != INVALID_SOCKET);
735         data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
736         g_assert (data->pipe [1] != INVALID_SOCKET);
737
738         server.sin_family = AF_INET;
739         server.sin_addr.s_addr = inet_addr ("127.0.0.1");
740         server.sin_port = 0;
741         if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
742                 g_print ("%d\n", WSAGetLastError ());
743                 g_assert (1 != 0);
744         }
745
746         len = sizeof (server);
747         getsockname (srv, (SOCKADDR *) &server, &len);
748         listen (srv, 1);
749         mono_thread_create (mono_get_root_domain (), connect_hack, &server);
750         len = sizeof (server);
751         data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
752         g_assert (data->pipe [0] != INVALID_SOCKET);
753         closesocket (srv);
754 #endif
755         mono_io_max_worker_threads = mono_max_worker_threads / 2;
756         if (mono_io_max_worker_threads < 10)
757                 mono_io_max_worker_threads = 10;
758
759         data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
760
761         if (data->epoll_disabled) {
762                 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
763                 g_assert (data->new_sem != NULL);
764         }
765         io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
766         g_assert (io_job_added != NULL);
767         InitializeCriticalSection (&io_queue_lock);
768         if (data->epoll_disabled) {
769                 mono_thread_create (mono_get_root_domain (), socket_io_poll_main, data);
770         }
771 #ifdef HAVE_EPOLL
772         else {
773                 mono_thread_create (mono_get_root_domain (), socket_io_epoll_main, data);
774         }
775 #endif
776         InterlockedCompareExchange (&data->inited, 1, 0);
777         LeaveCriticalSection (&data->io_lock);
778 }
779
780 static void
781 socket_io_add_poll (MonoSocketAsyncResult *state)
782 {
783         int events;
784         char msg [1];
785         MonoMList *list;
786         SocketIOData *data = &socket_io_data;
787
788 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32)
789         /* select() for connect() does not work well on the Mac. Bug #75436. */
790         /* Bug #77637 for the BSD 6 case */
791         /* Bug #78888 for the Windows case */
792         if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
793                 start_io_thread_or_queue (state);
794                 return;
795         }
796 #endif
797         WaitForSingleObject (data->new_sem, INFINITE);
798         if (data->newpfd == NULL)
799                 data->newpfd = g_new0 (mono_pollfd, 1);
800
801         EnterCriticalSection (&data->io_lock);
802         /* FIXME: 64 bit issue: handle can be a pointer on windows? */
803         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
804         if (list == NULL) {
805                 list = mono_mlist_alloc ((MonoObject*)state);
806         } else {
807                 list = mono_mlist_append (list, (MonoObject*)state);
808         }
809
810         events = get_events_from_list (list);
811         INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
812         mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
813         LeaveCriticalSection (&data->io_lock);
814         *msg = (char) state->operation;
815 #ifndef PLATFORM_WIN32
816         write (data->pipe [1], msg, 1);
817 #else
818         send ((SOCKET) data->pipe [1], msg, 1, 0);
819 #endif
820 }
821
822 #ifdef HAVE_EPOLL
823 static gboolean
824 socket_io_add_epoll (MonoSocketAsyncResult *state)
825 {
826         MonoMList *list;
827         SocketIOData *data = &socket_io_data;
828         struct epoll_event event;
829         int epoll_op, ievt;
830         int fd;
831
832         memset (&event, 0, sizeof (struct epoll_event));
833         fd = GPOINTER_TO_INT (state->handle);
834         EnterCriticalSection (&data->io_lock);
835         list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
836         if (list == NULL) {
837                 list = mono_mlist_alloc ((MonoObject*)state);
838                 epoll_op = EPOLL_CTL_ADD;
839         } else {
840                 list = mono_mlist_append (list, (MonoObject*)state);
841                 epoll_op = EPOLL_CTL_MOD;
842         }
843
844         ievt = get_events_from_list (list);
845         if ((ievt & MONO_POLLIN) != 0)
846                 event.events |= EPOLLIN;
847         if ((ievt & MONO_POLLOUT) != 0)
848                 event.events |= EPOLLOUT;
849
850         mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
851         event.data.fd = fd;
852 #ifdef EPOLL_DEBUG
853         g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
854 #endif
855         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
856                 int err = errno;
857                 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
858                         epoll_op = EPOLL_CTL_MOD;
859                         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
860                                 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
861                         }
862                 }
863         }
864
865         LeaveCriticalSection (&data->io_lock);
866         return TRUE;
867 }
868 #endif
869
870 static void
871 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
872 {
873         socket_io_init (&socket_io_data);
874         MONO_OBJECT_SETREF (state, ares, ares);
875 #ifdef HAVE_EPOLL
876         if (socket_io_data.epoll_disabled == FALSE) {
877                 if (socket_io_add_epoll (state))
878                         return;
879         }
880 #endif
881         socket_io_add_poll (state);
882 }
883
884 static gboolean
885 socket_io_filter (MonoObject *target, MonoObject *state)
886 {
887         gint op;
888         MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
889         MonoClass *klass;
890
891         if (target == NULL || state == NULL)
892                 return FALSE;
893
894         if (socket_async_call_klass == NULL) {
895                 klass = target->vtable->klass;
896                 /* Check if it's SocketAsyncCall in System.Net.Sockets
897                  * FIXME: check the assembly is signed correctly for extra care
898                  */
899                 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0 
900                                 && strcmp (mono_image_get_name (klass->image), "System") == 0
901                                 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
902                         socket_async_call_klass = klass;
903         }
904
905         if (process_async_call_klass == NULL) {
906                 klass = target->vtable->klass;
907                 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
908                  * FIXME: check the assembly is signed correctly for extra care
909                  */
910                 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0 
911                                 && strcmp (mono_image_get_name (klass->image), "System") == 0
912                                 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
913                         process_async_call_klass = klass;
914         }
915         /* return both when socket_async_call_klass has not been seen yet and when
916          * the object is not an instance of the class.
917          */
918         if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
919                 return FALSE;
920
921         op = sock_res->operation;
922         if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
923                 return FALSE;
924
925         return TRUE;
926 }
927
928 static void
929 mono_async_invoke (MonoAsyncResult *ares)
930 {
931         ASyncCall *ac = (ASyncCall *)ares->object_data;
932         MonoThread *thread = NULL;
933         MonoObject *res, *exc = NULL;
934         MonoArray *out_args = NULL;
935
936         if (ares->execution_context) {
937                 /* use captured ExecutionContext (if available) */
938                 thread = mono_thread_current ();
939                 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
940                 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
941         } else {
942                 ares->original_context = NULL;
943         }
944
945         ac->msg->exc = NULL;
946         res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
947         MONO_OBJECT_SETREF (ac, res, res);
948         MONO_OBJECT_SETREF (ac, msg->exc, exc);
949         MONO_OBJECT_SETREF (ac, out_args, out_args);
950
951         ares->completed = 1;
952
953         /* call async callback if cb_method != null*/
954         if (ac->cb_method) {
955                 MonoObject *exc = NULL;
956                 void *pa = &ares;
957                 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
958                 /* 'exc' will be the previous ac->msg->exc if not NULL and not
959                  * catched. If catched, this will be set to NULL and the
960                  * exception will not be printed. */
961                 MONO_OBJECT_SETREF (ac->msg, exc, exc);
962         }
963
964         /* restore original thread execution context if flow isn't suppressed, i.e. non null */
965         if (ares->original_context) {
966                 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
967                 ares->original_context = NULL;
968         }
969
970         /* notify listeners */
971         mono_monitor_enter ((MonoObject *) ares);
972         if (ares->handle != NULL) {
973                 ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
974                 SetEvent ((gpointer)(gsize)ac->wait_event);
975         }
976         mono_monitor_exit ((MonoObject *) ares);
977
978         EnterCriticalSection (&ares_lock);
979         mono_g_hash_table_remove (ares_htable, ares);
980         LeaveCriticalSection (&ares_lock);
981 }
982
983 void
984 mono_thread_pool_init ()
985 {
986         SYSTEM_INFO info;
987         int threads_per_cpu = THREADS_PER_CPU;
988
989         if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
990                 return;
991
992         MONO_GC_REGISTER_ROOT (ares_htable);
993         MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
994         InitializeCriticalSection (&socket_io_data.io_lock);
995         InitializeCriticalSection (&ares_lock);
996         ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
997         job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
998         g_assert (job_added != NULL);
999         GetSystemInfo (&info);
1000         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1001                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1002                 if (threads_per_cpu <= 0)
1003                         threads_per_cpu = THREADS_PER_CPU;
1004         }
1005
1006         mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
1007
1008         async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1009         g_assert (async_call_klass);
1010 }
1011
1012 MonoAsyncResult *
1013 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1014                       MonoObject *state)
1015 {
1016         MonoDomain *domain = mono_domain_get ();
1017         MonoAsyncResult *ares;
1018         ASyncCall *ac;
1019
1020         ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1021         MONO_OBJECT_SETREF (ac, msg, msg);
1022         MONO_OBJECT_SETREF (ac, state, state);
1023
1024         if (async_callback) {
1025                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1026                 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1027         }
1028
1029         ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1030         MONO_OBJECT_SETREF (ares, async_delegate, target);
1031
1032         EnterCriticalSection (&ares_lock);
1033         mono_g_hash_table_insert (ares_htable, ares, ares);
1034         LeaveCriticalSection (&ares_lock);
1035
1036         if (socket_io_filter (target, state)) {
1037                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1038                 return ares;
1039         }
1040
1041         start_thread_or_queue (ares);
1042         return ares;
1043 }
1044
1045 static void
1046 start_thread_or_queue (MonoAsyncResult *ares)
1047 {
1048         int busy, worker;
1049
1050         busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1051         worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1052         if (worker <= ++busy &&
1053             worker < mono_max_worker_threads) {
1054                 InterlockedIncrement (&mono_worker_threads);
1055                 InterlockedIncrement (&busy_worker_threads);
1056                 mono_thread_create (mono_get_root_domain (), async_invoke_thread, ares);
1057         } else {
1058                 append_job (&mono_delegate_section, &async_call_queue, (MonoObject*)ares);
1059                 ReleaseSemaphore (job_added, 1, NULL);
1060         }
1061 }
1062
1063 MonoObject *
1064 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1065 {
1066         ASyncCall *ac;
1067
1068         *exc = NULL;
1069         *out_args = NULL;
1070
1071         /* check if already finished */
1072         mono_monitor_enter ((MonoObject *) ares);
1073         
1074         if (ares->endinvoke_called) {
1075                 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System", 
1076                                               "InvalidOperationException");
1077                 mono_monitor_exit ((MonoObject *) ares);
1078                 return NULL;
1079         }
1080
1081         ares->endinvoke_called = 1;
1082         ac = (ASyncCall *)ares->object_data;
1083
1084         g_assert (ac != NULL);
1085
1086         /* wait until we are really finished */
1087         if (!ares->completed) {
1088                 if (ares->handle == NULL) {
1089                         ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1090                         g_assert(ac->wait_event != 0);
1091                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1092                 }
1093                 mono_monitor_exit ((MonoObject *) ares);
1094                 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1095         } else {
1096                 mono_monitor_exit ((MonoObject *) ares);
1097         }
1098
1099         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1100         *out_args = ac->out_args;
1101
1102         return ac->res;
1103 }
1104
1105 void
1106 mono_thread_pool_cleanup (void)
1107 {
1108         gint release;
1109
1110         EnterCriticalSection (&mono_delegate_section);
1111         free_queue (&async_call_queue);
1112         release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1113         LeaveCriticalSection (&mono_delegate_section);
1114         if (job_added)
1115                 ReleaseSemaphore (job_added, release, NULL);
1116
1117         socket_io_cleanup (&socket_io_data);
1118 }
1119
1120 static void
1121 append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar)
1122 {
1123         EnterCriticalSection (cs);
1124         if (list->array && (list->next_elem < mono_array_length (list->array))) {
1125                 mono_array_setref (list->array, list->next_elem, ar);
1126                 list->next_elem++;
1127                 LeaveCriticalSection (cs);
1128                 return;
1129         }
1130         if (!list->array) {
1131                 MONO_GC_REGISTER_ROOT (list->array);
1132                 list->array = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, 16);
1133         } else {
1134                 int count = list->next_elem - list->first_elem;
1135                 /* slide the array or create a larger one if it's full */
1136                 if (list->first_elem) {
1137                         mono_array_memcpy_refs (list->array, 0, list->array, list->first_elem, count);
1138                 } else {
1139                         MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) * 2);
1140                         mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1141                         list->array = newa;
1142                 }
1143                 list->first_elem = 0;
1144                 list->next_elem = count;
1145         }
1146         mono_array_setref (list->array, list->next_elem, ar);
1147         list->next_elem++;
1148         LeaveCriticalSection (cs);
1149 }
1150
1151 static MonoObject*
1152 dequeue_job (CRITICAL_SECTION *cs, TPQueue *list)
1153 {
1154         MonoObject *ar;
1155         int count;
1156
1157         EnterCriticalSection (cs);
1158         if (!list->array || list->first_elem == list->next_elem) {
1159                 LeaveCriticalSection (cs);
1160                 return NULL;
1161         }
1162         ar = mono_array_get (list->array, MonoObject*, list->first_elem);
1163         list->first_elem++;
1164         count = list->next_elem - list->first_elem;
1165         /* reduce the size of the array if it's mostly empty */
1166         if (mono_array_length (list->array) > 16 && count < (mono_array_length (list->array) / 3)) {
1167                 MonoArray *newa = mono_array_new (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) / 2);
1168                 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1169                 list->array = newa;
1170                 list->first_elem = 0;
1171                 list->next_elem = count;
1172         }
1173         LeaveCriticalSection (cs);
1174
1175         return ar;
1176 }
1177
1178 static void
1179 free_queue (TPQueue *list)
1180 {
1181         list->array = NULL;
1182         list->first_elem = list->next_elem = 0;
1183 }
1184
1185 static void
1186 async_invoke_thread (gpointer data)
1187 {
1188         MonoDomain *domain;
1189         MonoThread *thread;
1190         int workers, min;
1191  
1192         thread = mono_thread_current ();
1193         thread->threadpool_thread = TRUE;
1194         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1195
1196         for (;;) {
1197                 MonoAsyncResult *ar;
1198
1199                 ar = (MonoAsyncResult *) data;
1200                 if (ar) {
1201                         /* worker threads invokes methods in different domains,
1202                          * so we need to set the right domain here */
1203                         domain = ((MonoObject *)ar)->vtable->domain;
1204                         mono_thread_push_appdomain_ref (domain);
1205                         if (mono_domain_set (domain, FALSE)) {
1206                                 ASyncCall *ac;
1207
1208                                 mono_async_invoke (ar);
1209                                 ac = (ASyncCall *) ar->object_data;
1210                                 /*
1211                                 if (ac->msg->exc != NULL)
1212                                         mono_unhandled_exception (ac->msg->exc);
1213                                 */
1214                                 mono_domain_set (mono_get_root_domain (), TRUE);
1215                         }
1216                         mono_thread_pop_appdomain_ref ();
1217                         InterlockedDecrement (&busy_worker_threads);
1218                 }
1219
1220                 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1221
1222                 if (!data) {
1223                         guint32 wr;
1224                         int timeout = 10000;
1225                         guint32 start_time = GetTickCount ();
1226                         
1227                         do {
1228                                 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1229                                 if (THREAD_WANTS_A_BREAK (thread))
1230                                         mono_thread_interruption_checkpoint ();
1231                         
1232                                 timeout -= GetTickCount () - start_time;
1233                         
1234                                 if (wr != WAIT_TIMEOUT)
1235                                         data = dequeue_job (&mono_delegate_section, &async_call_queue);
1236                         }
1237                         while (!data && timeout > 0);
1238                 }
1239
1240                 if (!data) {
1241                         workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1242                         min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1); 
1243         
1244                         while (!data && workers <= min) {
1245                                 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1246                                 if (THREAD_WANTS_A_BREAK (thread))
1247                                         mono_thread_interruption_checkpoint ();
1248                         
1249                                 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1250                                 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1251                                 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1); 
1252                         }
1253                 }
1254         
1255                 if (!data) {
1256                         InterlockedDecrement (&mono_worker_threads);
1257                         return;
1258                 }
1259                 
1260                 InterlockedIncrement (&busy_worker_threads);
1261         }
1262
1263         g_assert_not_reached ();
1264 }
1265
1266 void
1267 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1268 {
1269         gint busy, busy_io;
1270
1271         MONO_ARCH_SAVE_REGS;
1272
1273         busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1274         busy_io = (gint) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
1275         *workerThreads = mono_max_worker_threads - busy;
1276         *completionPortThreads = mono_io_max_worker_threads - busy_io;
1277 }
1278
1279 void
1280 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1281 {
1282         MONO_ARCH_SAVE_REGS;
1283
1284         *workerThreads = mono_max_worker_threads;
1285         *completionPortThreads = mono_io_max_worker_threads;
1286 }
1287
1288 void
1289 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1290 {
1291         gint workers, workers_io;
1292
1293         MONO_ARCH_SAVE_REGS;
1294
1295         workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1296         workers_io = (gint) InterlockedCompareExchange (&mono_io_min_worker_threads, 0, -1);
1297
1298         *workerThreads = workers;
1299         *completionPortThreads = workers_io;
1300 }
1301
1302 MonoBoolean
1303 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1304 {
1305         MONO_ARCH_SAVE_REGS;
1306
1307         if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1308                 return FALSE;
1309
1310         if (completionPortThreads < 0 || completionPortThreads > mono_io_max_worker_threads)
1311                 return FALSE;
1312
1313         InterlockedExchange (&mono_min_worker_threads, workerThreads);
1314         InterlockedExchange (&mono_io_min_worker_threads, completionPortThreads);
1315         /* FIXME: should actually start the idle threads if needed */
1316         return TRUE;
1317 }
1318
1319 MonoBoolean
1320 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1321 {
1322         MONO_ARCH_SAVE_REGS;
1323
1324         if (workerThreads < mono_max_worker_threads)
1325                 return FALSE;
1326
1327         if (completionPortThreads < mono_io_max_worker_threads)
1328                 return FALSE;
1329
1330         InterlockedExchange (&mono_max_worker_threads, workerThreads);
1331         InterlockedExchange (&mono_io_max_worker_threads, completionPortThreads);
1332         return TRUE;
1333 }