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