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