2006-05-30 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / threadpool.c
1 /*
2  * threadpool.c: global thread pool
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Gonzalo Paniagua Javier (gonzalo@ximian.com)
7  *
8  * (C) 2001-2003 Ximian, Inc.
9  * (c) 2004,2005 Novell, Inc. (http://www.novell.com)
10  */
11
12 #include <config.h>
13 #include <glib.h>
14
15 #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 (pfd, 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 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6)
768         /* select() for connect() does not work well on the Mac. Bug #75436. */
769         /* Bug #77637 for the BSD 6 case */
770         if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
771                 start_io_thread_or_queue (state);
772                 return;
773         }
774 #endif
775         WaitForSingleObject (data->new_sem, INFINITE);
776         if (data->newpfd == NULL)
777                 data->newpfd = g_new0 (mono_pollfd, 1);
778
779         EnterCriticalSection (&data->io_lock);
780         list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
781         if (list == NULL) {
782                 list = g_slist_alloc ();
783                 list->data = state;
784         } else {
785                 list = g_slist_append (list, state);
786         }
787
788         events = get_events_from_list (list);
789         INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
790         g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
791         LeaveCriticalSection (&data->io_lock);
792         *msg = (char) state->operation;
793 #ifndef PLATFORM_WIN32
794         write (data->pipe [1], msg, 1);
795 #else
796         send ((SOCKET) data->pipe [1], msg, 1, 0);
797 #endif
798 }
799
800 #ifdef HAVE_EPOLL
801 static gboolean
802 socket_io_add_epoll (MonoSocketAsyncResult *state)
803 {
804         GSList *list;
805         SocketIOData *data = &socket_io_data;
806         struct epoll_event event;
807         int epoll_op, ievt;
808         int fd;
809
810         memset (&event, 0, sizeof (struct epoll_event));
811         fd = GPOINTER_TO_INT (state->handle);
812         EnterCriticalSection (&data->io_lock);
813         list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
814         if (list == NULL) {
815                 list = g_slist_alloc ();
816                 list->data = state;
817                 epoll_op = EPOLL_CTL_ADD;
818         } else {
819                 list = g_slist_append (list, state);
820                 epoll_op = EPOLL_CTL_MOD;
821         }
822
823         ievt = get_events_from_list (list);
824         if ((ievt & MONO_POLLIN) != 0)
825                 event.events |= EPOLLIN;
826         if ((ievt & MONO_POLLOUT) != 0)
827                 event.events |= EPOLLOUT;
828
829         g_hash_table_replace (data->sock_to_state, state->handle, list);
830         event.data.fd = fd;
831 #ifdef EPOLL_DEBUG
832         g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
833 #endif
834         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
835                 int err = errno;
836                 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
837                         epoll_op = EPOLL_CTL_MOD;
838                         if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
839                                 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
840                         }
841                 }
842         }
843
844         LeaveCriticalSection (&data->io_lock);
845         return TRUE;
846 }
847 #endif
848
849 static void
850 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
851 {
852         socket_io_init (&socket_io_data);
853         MONO_OBJECT_SETREF (state, ares, ares);
854 #ifdef HAVE_EPOLL
855         if (socket_io_data.epoll_disabled == FALSE) {
856                 if (socket_io_add_epoll (state))
857                         return;
858         }
859 #endif
860         socket_io_add_poll (state);
861 }
862
863 static gboolean
864 socket_io_filter (MonoObject *target, MonoObject *state)
865 {
866         gint op;
867         MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
868         MonoClass *klass;
869
870         if (target == NULL || state == NULL)
871                 return FALSE;
872
873         if (socket_async_call_klass == NULL) {
874                 klass = target->vtable->klass;
875                 /* Check if it's SocketAsyncCall in System
876                  * FIXME: check the assembly is signed correctly for extra care
877                  */
878                 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0 
879                                 && strcmp (mono_image_get_name (klass->image), "System") == 0
880                                 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
881                         socket_async_call_klass = klass;
882         }
883
884         /* return both when socket_async_call_klass has not been seen yet and when
885          * the object is not an instance of the class.
886          */
887         if (target->vtable->klass != socket_async_call_klass)
888                 return FALSE;
889
890         op = sock_res->operation;
891         if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
892                 return FALSE;
893
894         return TRUE;
895 }
896
897 static void
898 mono_async_invoke (MonoAsyncResult *ares)
899 {
900         ASyncCall *ac = (ASyncCall *)ares->data;
901         MonoThread *thread = NULL;
902
903         if (ares->execution_context) {
904                 /* use captured ExecutionContext (if available) */
905                 thread = mono_thread_current ();
906                 MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
907                 MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
908         } else {
909                 ares->original_context = NULL;
910         }
911
912         ac->msg->exc = NULL;
913         ac->res = mono_message_invoke (ares->async_delegate, ac->msg, 
914                                        &ac->msg->exc, &ac->out_args);
915
916         ares->completed = 1;
917
918         /* call async callback if cb_method != null*/
919         if (ac->cb_method) {
920                 MonoObject *exc = NULL;
921                 void *pa = &ares;
922                 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
923                 /* 'exc' will be the previous ac->msg->exc if not NULL and not
924                  * catched. If catched, this will be set to NULL and the
925                  * exception will not be printed. */
926                 MONO_OBJECT_SETREF (ac->msg, exc, exc);
927         }
928
929         /* restore original thread execution context if flow isn't suppressed, i.e. non null */
930         if (ares->original_context) {
931                 MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
932                 ares->original_context = NULL;
933         }
934
935         /* notify listeners */
936         mono_monitor_enter ((MonoObject *) ares);
937         if (ares->handle != NULL) {
938                 ac->wait_event = ((MonoWaitHandle *) ares->handle)->handle;
939                 SetEvent (ac->wait_event);
940         }
941         mono_monitor_exit ((MonoObject *) ares);
942
943         EnterCriticalSection (&ares_lock);
944         mono_g_hash_table_remove (ares_htable, ares);
945         LeaveCriticalSection (&ares_lock);
946 }
947
948 void
949 mono_thread_pool_init ()
950 {
951         SYSTEM_INFO info;
952         int threads_per_cpu = THREADS_PER_CPU;
953
954         if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
955                 return;
956
957         MONO_GC_REGISTER_ROOT (ares_htable);
958         InitializeCriticalSection (&socket_io_data.io_lock);
959         InitializeCriticalSection (&ares_lock);
960         ares_htable = mono_g_hash_table_new (NULL, NULL);
961         job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
962         GetSystemInfo (&info);
963         if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
964                 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
965                 if (threads_per_cpu <= 0)
966                         threads_per_cpu = THREADS_PER_CPU;
967         }
968
969         mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
970 }
971
972 MonoAsyncResult *
973 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
974                       MonoObject *state)
975 {
976         MonoDomain *domain = mono_domain_get ();
977         MonoAsyncResult *ares;
978         ASyncCall *ac;
979
980 #ifdef HAVE_BOEHM_GC
981         ac = GC_MALLOC (sizeof (ASyncCall));
982 #else
983         /* We'll leak the event if creaated... */
984         ac = g_new0 (ASyncCall, 1);
985 #endif
986         ac->wait_event = NULL;
987         ac->msg = msg;
988         ac->state = state;
989
990         if (async_callback) {
991                 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
992                 ac->cb_target = async_callback;
993         }
994
995         ares = mono_async_result_new (domain, NULL, ac->state, ac);
996         MONO_OBJECT_SETREF (ares, async_delegate, target);
997
998         EnterCriticalSection (&ares_lock);
999         mono_g_hash_table_insert (ares_htable, ares, ares);
1000         LeaveCriticalSection (&ares_lock);
1001
1002         if (socket_io_filter (target, state)) {
1003                 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1004                 return ares;
1005         }
1006
1007         start_thread_or_queue (ares);
1008         return ares;
1009 }
1010
1011 static void
1012 start_thread_or_queue (MonoAsyncResult *ares)
1013 {
1014         int busy, worker;
1015         MonoDomain *domain;
1016
1017         busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1018         worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1019         if (worker <= ++busy &&
1020             worker < mono_max_worker_threads) {
1021                 InterlockedIncrement (&mono_worker_threads);
1022                 InterlockedIncrement (&busy_worker_threads);
1023                 domain = ((MonoObject *) ares)->vtable->domain;
1024                 mono_thread_create (mono_get_root_domain (), async_invoke_thread, ares);
1025         } else {
1026                 append_job (&mono_delegate_section, &async_call_queue, ares);
1027                 ReleaseSemaphore (job_added, 1, NULL);
1028         }
1029 }
1030
1031 MonoObject *
1032 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1033 {
1034         ASyncCall *ac;
1035
1036         *exc = NULL;
1037         *out_args = NULL;
1038
1039         /* check if already finished */
1040         mono_monitor_enter ((MonoObject *) ares);
1041         
1042         if (ares->endinvoke_called) {
1043                 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System", 
1044                                               "InvalidOperationException");
1045                 mono_monitor_exit ((MonoObject *) ares);
1046                 return NULL;
1047         }
1048
1049         ares->endinvoke_called = 1;
1050         ac = (ASyncCall *)ares->data;
1051
1052         g_assert (ac != NULL);
1053
1054         /* wait until we are really finished */
1055         if (!ares->completed) {
1056                 if (ares->handle == NULL) {
1057                         ac->wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1058                         MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), ac->wait_event));
1059                 }
1060                 mono_monitor_exit ((MonoObject *) ares);
1061                 WaitForSingleObjectEx (ac->wait_event, INFINITE, TRUE);
1062         } else {
1063                 mono_monitor_exit ((MonoObject *) ares);
1064         }
1065
1066         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1067         *out_args = ac->out_args;
1068
1069         return ac->res;
1070 }
1071
1072 void
1073 mono_thread_pool_cleanup (void)
1074 {
1075         gint release;
1076
1077         EnterCriticalSection (&mono_delegate_section);
1078         g_list_free (async_call_queue);
1079         async_call_queue = NULL;
1080         release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1081         LeaveCriticalSection (&mono_delegate_section);
1082         if (job_added)
1083                 ReleaseSemaphore (job_added, release, NULL);
1084
1085         socket_io_cleanup (&socket_io_data);
1086 }
1087
1088 static void
1089 append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar)
1090 {
1091         GList *tmp, *list;
1092
1093         EnterCriticalSection (cs);
1094         list = *plist;
1095         if (list == NULL) {
1096                 list = g_list_append (list, ar); 
1097         } else {
1098                 for (tmp = list; tmp && tmp->data != NULL; tmp = tmp->next);
1099                 if (tmp == NULL) {
1100                         list = g_list_append (list, ar); 
1101                 } else {
1102                         tmp->data = ar;
1103                 }
1104         }
1105         *plist = list;
1106         LeaveCriticalSection (cs);
1107 }
1108
1109 static gpointer
1110 dequeue_job (CRITICAL_SECTION *cs, GList **plist)
1111 {
1112         gpointer ar = NULL;
1113         GList *tmp, *tmp2, *list;
1114
1115         EnterCriticalSection (cs);
1116         list = *plist;
1117         tmp = list;
1118         if (tmp) {
1119                 ar = tmp->data;
1120                 tmp->data = NULL;
1121                 tmp2 = tmp;
1122                 for (tmp2 = tmp; tmp2->next != NULL; tmp2 = tmp2->next);
1123                 if (tmp2 != tmp) {
1124                         list = tmp->next;
1125                         tmp->next = NULL;
1126                         tmp2->next = tmp;
1127                         tmp->prev = tmp2;
1128                 }
1129         }
1130         *plist = list;
1131         LeaveCriticalSection (cs);
1132
1133         return ar;
1134 }
1135
1136 static void
1137 async_invoke_thread (gpointer data)
1138 {
1139         MonoDomain *domain;
1140         MonoThread *thread;
1141         int workers, min;
1142  
1143         thread = mono_thread_current ();
1144         thread->threadpool_thread = TRUE;
1145         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1146
1147         for (;;) {
1148                 MonoAsyncResult *ar;
1149
1150                 ar = (MonoAsyncResult *) data;
1151                 if (ar) {
1152                         /* worker threads invokes methods in different domains,
1153                          * so we need to set the right domain here */
1154                         domain = ((MonoObject *)ar)->vtable->domain;
1155                         mono_thread_push_appdomain_ref (domain);
1156                         if (mono_domain_set (domain, FALSE)) {
1157                                 ASyncCall *ac;
1158
1159                                 mono_async_invoke (ar);
1160                                 ac = (ASyncCall *) ar->data;
1161                                 /*
1162                                 if (ac->msg->exc != NULL)
1163                                         mono_unhandled_exception (ac->msg->exc);
1164                                 */
1165                                 mono_domain_set (mono_get_root_domain (), TRUE);
1166                         }
1167                         mono_thread_pop_appdomain_ref ();
1168                         InterlockedDecrement (&busy_worker_threads);
1169                 }
1170
1171                 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1172
1173                 if (!data) {
1174                         guint32 wr;
1175                         int timeout = 10000;
1176                         guint32 start_time = GetTickCount ();
1177                         
1178                         do {
1179                                 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1180                                 if (THREAD_WANTS_A_BREAK (thread))
1181                                         mono_thread_interruption_checkpoint ();
1182                         
1183                                 timeout -= GetTickCount () - start_time;
1184                         
1185                                 if (wr != WAIT_TIMEOUT)
1186                                         data = dequeue_job (&mono_delegate_section, &async_call_queue);
1187                         }
1188                         while (!data && timeout > 0);
1189                 }
1190
1191                 if (!data) {
1192                         workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1193                         min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1); 
1194         
1195                         while (!data && workers <= min) {
1196                                 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1197                                 if (THREAD_WANTS_A_BREAK (thread))
1198                                         mono_thread_interruption_checkpoint ();
1199                         
1200                                 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1201                                 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
1202                                 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1); 
1203                         }
1204                 }
1205         
1206                 if (!data) {
1207                         InterlockedDecrement (&mono_worker_threads);
1208                         return;
1209                 }
1210                 
1211                 InterlockedIncrement (&busy_worker_threads);
1212         }
1213
1214         g_assert_not_reached ();
1215 }
1216
1217 void
1218 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1219 {
1220         gint busy;
1221
1222         MONO_ARCH_SAVE_REGS;
1223
1224         busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1225         *workerThreads = mono_max_worker_threads - busy;
1226         *completionPortThreads = 0;
1227 }
1228
1229 void
1230 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1231 {
1232         MONO_ARCH_SAVE_REGS;
1233
1234         *workerThreads = mono_max_worker_threads;
1235         *completionPortThreads = 0;
1236 }
1237
1238 void
1239 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1240 {
1241         gint workers;
1242
1243         MONO_ARCH_SAVE_REGS;
1244
1245         workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1246         *workerThreads = workers;
1247         *completionPortThreads = 0;
1248 }
1249
1250 MonoBoolean
1251 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1252 {
1253         MONO_ARCH_SAVE_REGS;
1254
1255         if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1256                 return FALSE;
1257         InterlockedExchange (&mono_min_worker_threads, workerThreads);
1258         /* FIXME: should actually start the idle threads if needed */
1259         return TRUE;
1260 }
1261