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