2 * threadpool.c: global thread pool
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
15 #define THREADS_PER_CPU 10 /* 20 + THREADS_PER_CPU * number of CPUs */
16 #define THREAD_EXIT_TIMEOUT 1000
17 #define INITIAL_QUEUE_LENGTH 128
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/tabledefs.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/threads-types.h>
23 #include <mono/metadata/threadpool-internals.h>
24 #include <mono/metadata/exception.h>
25 #include <mono/metadata/file-io.h>
26 #include <mono/metadata/monitor.h>
27 #include <mono/metadata/mono-mlist.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/metadata/socket-io.h>
30 #include <mono/io-layer/io-layer.h>
31 #include <mono/metadata/gc-internal.h>
32 #include <mono/utils/mono-time.h>
33 #include <mono/utils/mono-proclib.h>
35 #ifdef HAVE_SYS_TIME_H
38 #include <sys/types.h>
44 #ifdef HAVE_SYS_SOCKET_H
45 #include <sys/socket.h>
47 #include <mono/utils/mono-poll.h>
49 #include <sys/epoll.h>
52 #ifndef DISABLE_SOCKETS
53 #include "mono/io-layer/socket-wrappers.h"
56 #include "threadpool.h"
58 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
59 ThreadState_SuspendRequested)) != 0)
63 /* maximum number of worker threads */
64 static int mono_max_worker_threads;
65 static int mono_min_worker_threads;
66 static int mono_io_max_worker_threads;
67 static int mono_io_min_worker_threads;
69 /* current number of worker threads */
70 static int mono_worker_threads = 0;
71 static int io_worker_threads = 0;
73 /* current number of busy threads */
74 static int busy_worker_threads = 0;
75 static int busy_io_worker_threads;
77 /* mono_thread_pool_init called */
79 /* started idle threads */
80 static int tp_idle_started;
83 /* we use this to store a reference to the AsyncResult to avoid GC */
84 static MonoGHashTable *ares_htable = NULL;
86 static CRITICAL_SECTION ares_lock;
87 static CRITICAL_SECTION io_queue_lock;
88 static int pending_io_items;
91 CRITICAL_SECTION io_lock; /* access to sock_to_state */
94 MonoGHashTable *sock_to_state;
96 HANDLE new_sem; /* access to newpfd and write side of the pipe */
98 gboolean epoll_disabled;
104 static SocketIOData socket_io_data;
106 /* we append a job */
107 static HANDLE job_added;
108 static HANDLE io_job_added;
110 /* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
113 MonoMethodMessage *msg;
114 MonoMethod *cb_method;
115 MonoDelegate *cb_target;
119 /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
129 static void async_invoke_thread (gpointer data);
130 static void append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar);
131 static void start_thread_or_queue (MonoAsyncResult *ares);
132 static void start_tpthread (MonoAsyncResult *ares);
133 static void mono_async_invoke (MonoAsyncResult *ares);
134 static MonoObject* dequeue_job (CRITICAL_SECTION *cs, TPQueue *list);
135 static void free_queue (TPQueue *list);
137 static TPQueue async_call_queue = {NULL, 0, 0};
138 static TPQueue async_io_queue = {NULL, 0, 0};
140 static MonoClass *async_call_klass;
141 static MonoClass *socket_async_call_klass;
142 static MonoClass *process_async_call_klass;
144 #define INIT_POLLFD(a, b, c) {(a)->fd = b; (a)->events = c; (a)->revents = 0;}
153 AIO_OP_RECV_JUST_CALLBACK,
154 AIO_OP_SEND_JUST_CALLBACK,
159 #ifdef DISABLE_SOCKETS
160 #define socket_io_cleanup(x)
163 socket_io_cleanup (SocketIOData *data)
167 if (data->inited == 0)
170 EnterCriticalSection (&data->io_lock);
172 #ifdef PLATFORM_WIN32
173 closesocket (data->pipe [0]);
174 closesocket (data->pipe [1]);
176 close (data->pipe [0]);
177 close (data->pipe [1]);
182 CloseHandle (data->new_sem);
183 data->new_sem = NULL;
184 mono_g_hash_table_destroy (data->sock_to_state);
185 data->sock_to_state = NULL;
186 free_queue (&async_io_queue);
187 release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
189 ReleaseSemaphore (io_job_added, release, NULL);
190 g_free (data->newpfd);
193 if (FALSE == data->epoll_disabled)
194 close (data->epollfd);
196 LeaveCriticalSection (&data->io_lock);
200 get_event_from_state (MonoSocketAsyncResult *state)
202 switch (state->operation) {
205 case AIO_OP_RECV_JUST_CALLBACK:
206 case AIO_OP_RECEIVEFROM:
207 case AIO_OP_READPIPE:
210 case AIO_OP_SEND_JUST_CALLBACK:
214 default: /* Should never happen */
215 g_print ("get_event_from_state: unknown value in switch!!!\n");
221 get_events_from_list (MonoMList *list)
223 MonoSocketAsyncResult *state;
226 while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
227 events |= get_event_from_state (state);
228 list = mono_mlist_next (list);
234 #define ICALL_RECV(x) ves_icall_System_Net_Sockets_Socket_Receive_internal (\
235 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
236 x->socket_flags, &x->error);
238 #define ICALL_SEND(x) ves_icall_System_Net_Sockets_Socket_Send_internal (\
239 (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
240 x->socket_flags, &x->error);
242 #endif /* !DISABLE_SOCKETS */
245 unregister_job (MonoAsyncResult *obj)
247 EnterCriticalSection (&ares_lock);
248 mono_g_hash_table_remove (ares_htable, obj);
249 LeaveCriticalSection (&ares_lock);
253 threadpool_jobs_inc (MonoObject *obj)
256 InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
260 threadpool_jobs_dec (MonoObject *obj)
262 MonoDomain *domain = obj->vtable->domain;
263 int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
264 if (remaining_jobs == 0 && domain->cleanup_semaphore) {
265 ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
271 #ifndef DISABLE_SOCKETS
273 async_invoke_io_thread (gpointer data)
277 const gchar *version;
279 thread = mono_thread_current ();
281 version = mono_get_runtime_info ()->framework_version;
283 MonoSocketAsyncResult *state;
286 state = (MonoSocketAsyncResult *) data;
288 InterlockedDecrement (&pending_io_items);
290 switch (state->operation) {
292 state->total = ICALL_RECV (state);
295 state->total = ICALL_SEND (state);
299 /* worker threads invokes methods in different domains,
300 * so we need to set the right domain here */
301 domain = ((MonoObject *)ar)->vtable->domain;
305 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
306 threadpool_jobs_dec ((MonoObject *)ar);
310 mono_thread_push_appdomain_ref (domain);
311 if (threadpool_jobs_dec ((MonoObject *)ar)) {
314 mono_thread_pop_appdomain_ref ();
317 if (mono_domain_set (domain, FALSE)) {
320 mono_async_invoke (ar);
321 ac = (ASyncCall *) ar->object_data;
323 if (ac->msg->exc != NULL)
324 mono_unhandled_exception (ac->msg->exc);
326 mono_domain_set (mono_get_root_domain (), TRUE);
328 mono_thread_pop_appdomain_ref ();
329 InterlockedDecrement (&busy_io_worker_threads);
330 /* If the callee changes the background status, set it back to TRUE */
331 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
332 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
336 data = dequeue_job (&io_queue_lock, &async_io_queue);
340 int timeout = THREAD_EXIT_TIMEOUT;
341 guint32 start_time = mono_msec_ticks ();
344 wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
345 if (THREAD_WANTS_A_BREAK (thread))
346 mono_thread_interruption_checkpoint ();
348 timeout -= mono_msec_ticks () - start_time;
350 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION)
351 data = dequeue_job (&io_queue_lock, &async_io_queue);
353 while (!data && timeout > 0);
357 if (InterlockedDecrement (&io_worker_threads) < 2) {
358 /* If we have pending items, keep the thread alive */
359 if (InterlockedCompareExchange (&pending_io_items, 0, 0) != 0) {
360 InterlockedIncrement (&io_worker_threads);
367 InterlockedIncrement (&busy_io_worker_threads);
370 g_assert_not_reached ();
374 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
378 busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
379 worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1);
380 if (worker <= ++busy &&
381 worker < mono_io_max_worker_threads) {
382 InterlockedIncrement (&busy_io_worker_threads);
383 InterlockedIncrement (&io_worker_threads);
384 threadpool_jobs_inc ((MonoObject *)ares);
385 mono_thread_create_internal (mono_get_root_domain (), async_invoke_io_thread, ares, TRUE);
387 append_job (&io_queue_lock, &async_io_queue, (MonoObject*)ares);
388 ReleaseSemaphore (io_job_added, 1, NULL);
393 process_io_event (MonoMList *list, int event)
395 MonoSocketAsyncResult *state;
401 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
402 if (get_event_from_state (state) == event)
405 list = mono_mlist_next (list);
409 oldlist = mono_mlist_remove_item (oldlist, list);
411 g_print ("Dispatching event %d on socket %d\n", event, state->handle);
413 InterlockedIncrement (&pending_io_items);
414 start_io_thread_or_queue (state);
421 mark_bad_fds (mono_pollfd *pfds, int nfds)
427 for (i = 0; i < nfds; i++) {
432 ret = mono_poll (pfd, 1, 0);
433 if (ret == -1 && errno == EBADF) {
434 pfd->revents |= MONO_POLLNVAL;
436 } else if (ret == 1) {
445 socket_io_poll_main (gpointer p)
447 #define INITIAL_POLLFD_SIZE 1024
448 #define POLL_ERRORS (MONO_POLLERR | MONO_POLLHUP | MONO_POLLNVAL)
449 SocketIOData *data = p;
456 thread = mono_thread_current ();
458 allocated = INITIAL_POLLFD_SIZE;
459 pfds = g_new0 (mono_pollfd, allocated);
460 INIT_POLLFD (pfds, data->pipe [0], MONO_POLLIN);
461 for (i = 1; i < allocated; i++)
462 INIT_POLLFD (&pfds [i], -1, 0);
472 if (THREAD_WANTS_A_BREAK (thread))
473 mono_thread_interruption_checkpoint ();
476 nsock = mono_poll (pfds, maxfd, -1);
477 } while (nsock == -1 && errno == EINTR);
480 * Apart from EINTR, we only check EBADF, for the rest:
481 * EINVAL: mono_poll() 'protects' us from descriptor
482 * numbers above the limit if using select() by marking
483 * then as MONO_POLLERR. If a system poll() is being
484 * used, the number of descriptor we're passing will not
485 * be over sysconf(_SC_OPEN_MAX), as the error would have
486 * happened when opening.
488 * EFAULT: we own the memory pointed by pfds.
489 * ENOMEM: we're doomed anyway
493 if (nsock == -1 && errno == EBADF) {
494 pfds->revents = 0; /* Just in case... */
495 nsock = mark_bad_fds (pfds, maxfd);
498 if ((pfds->revents & POLL_ERRORS) != 0) {
499 /* We're supposed to die now, as the pipe has been closed */
501 socket_io_cleanup (data);
505 /* Got a new socket */
506 if ((pfds->revents & MONO_POLLIN) != 0) {
509 for (i = 1; i < allocated; i++) {
511 if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
515 if (i == allocated) {
520 allocated = allocated * 2;
521 pfds = g_renew (mono_pollfd, oldfd, allocated);
523 for (; i < allocated; i++)
524 INIT_POLLFD (&pfds [i], -1, 0);
526 #ifndef PLATFORM_WIN32
527 nread = read (data->pipe [0], one, 1);
529 nread = recv ((SOCKET) data->pipe [0], one, 1, 0);
533 return; /* we're closed */
536 INIT_POLLFD (&pfds [i], data->newpfd->fd, data->newpfd->events);
537 ReleaseSemaphore (data->new_sem, 1, NULL);
546 EnterCriticalSection (&data->io_lock);
547 if (data->inited == 0) {
549 LeaveCriticalSection (&data->io_lock);
550 return; /* cleanup called */
553 for (i = 1; i < maxfd && nsock > 0; i++) {
555 if (pfd->fd == -1 || pfd->revents == 0)
559 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
560 if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
561 list = process_io_event (list, MONO_POLLIN);
564 if (list != NULL && (pfd->revents & (MONO_POLLOUT | POLL_ERRORS)) != 0) {
565 list = process_io_event (list, MONO_POLLOUT);
569 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
570 pfd->events = get_events_from_list (list);
572 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
578 LeaveCriticalSection (&data->io_lock);
583 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
585 socket_io_epoll_main (gpointer p)
590 struct epoll_event *events, *evt;
591 const int nevents = 512;
595 epollfd = data->epollfd;
596 thread = mono_thread_current ();
597 events = g_new0 (struct epoll_event, nevents);
602 if (THREAD_WANTS_A_BREAK (thread))
603 mono_thread_interruption_checkpoint ();
606 g_print ("epoll_wait init\n");
608 ready = epoll_wait (epollfd, events, nevents, -1);
612 g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
616 } while (ready == -1 && errno == EINTR);
622 g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
628 EnterCriticalSection (&data->io_lock);
629 if (data->inited == 0) {
631 g_print ("data->inited == 0\n");
635 return; /* cleanup called */
638 for (i = 0; i < ready; i++) {
644 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
646 g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
648 if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
649 list = process_io_event (list, MONO_POLLIN);
652 if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
653 list = process_io_event (list, MONO_POLLOUT);
657 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
658 evt->events = get_events_from_list (list);
660 g_print ("MOD %d to %d\n", fd, evt->events);
662 if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
663 if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
666 g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
672 mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
674 g_print ("DEL %d\n", fd);
676 epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
679 LeaveCriticalSection (&data->io_lock);
685 * select/poll wake up when a socket is closed, but epoll just removes
686 * the socket from its internal list without notification.
689 mono_thread_pool_remove_socket (int sock)
691 MonoMList *list, *next;
692 MonoSocketAsyncResult *state;
694 if (socket_io_data.inited == FALSE)
697 EnterCriticalSection (&socket_io_data.io_lock);
698 list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
700 mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
702 LeaveCriticalSection (&socket_io_data.io_lock);
705 state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
706 if (state->operation == AIO_OP_RECEIVE)
707 state->operation = AIO_OP_RECV_JUST_CALLBACK;
708 else if (state->operation == AIO_OP_SEND)
709 state->operation = AIO_OP_SEND_JUST_CALLBACK;
711 next = mono_mlist_remove_item (list, list);
712 list = process_io_event (list, MONO_POLLIN);
714 process_io_event (list, MONO_POLLOUT);
720 #ifdef PLATFORM_WIN32
722 connect_hack (gpointer x)
724 struct sockaddr_in *addr = (struct sockaddr_in *) x;
727 while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
730 g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
731 g_assert (WSAGetLastError ());
738 socket_io_init (SocketIOData *data)
740 #ifdef PLATFORM_WIN32
741 struct sockaddr_in server;
742 struct sockaddr_in client;
748 inited = InterlockedCompareExchange (&data->inited, -1, -1);
752 EnterCriticalSection (&data->io_lock);
753 inited = InterlockedCompareExchange (&data->inited, -1, -1);
755 LeaveCriticalSection (&data->io_lock);
760 data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
761 if (FALSE == data->epoll_disabled) {
762 data->epollfd = epoll_create (256);
763 data->epoll_disabled = (data->epollfd == -1);
764 if (data->epoll_disabled && g_getenv ("MONO_DEBUG"))
765 g_message ("epoll_create() failed. Using plain poll().");
770 data->epoll_disabled = TRUE;
773 #ifndef PLATFORM_WIN32
774 if (data->epoll_disabled) {
775 if (pipe (data->pipe) != 0) {
785 srv = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
786 g_assert (srv != INVALID_SOCKET);
787 data->pipe [1] = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
788 g_assert (data->pipe [1] != INVALID_SOCKET);
790 server.sin_family = AF_INET;
791 server.sin_addr.s_addr = inet_addr ("127.0.0.1");
793 if (bind (srv, (SOCKADDR *) &server, sizeof (server))) {
794 g_print ("%d\n", WSAGetLastError ());
798 len = sizeof (server);
799 getsockname (srv, (SOCKADDR *) &server, &len);
801 mono_thread_create (mono_get_root_domain (), connect_hack, &server);
802 len = sizeof (server);
803 data->pipe [0] = accept (srv, (SOCKADDR *) &client, &len);
804 g_assert (data->pipe [0] != INVALID_SOCKET);
807 mono_io_max_worker_threads = mono_max_worker_threads / 2;
808 if (mono_io_max_worker_threads < 10)
809 mono_io_max_worker_threads = 10;
811 data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
813 if (data->epoll_disabled) {
814 data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
815 g_assert (data->new_sem != NULL);
817 io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
818 g_assert (io_job_added != NULL);
819 if (data->epoll_disabled) {
820 mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
824 mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
827 InterlockedCompareExchange (&data->inited, 1, 0);
828 LeaveCriticalSection (&data->io_lock);
832 socket_io_add_poll (MonoSocketAsyncResult *state)
837 SocketIOData *data = &socket_io_data;
840 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
841 /* select() for connect() does not work well on the Mac. Bug #75436. */
842 /* Bug #77637 for the BSD 6 case */
843 /* Bug #78888 for the Windows case */
844 if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
845 start_io_thread_or_queue (state);
849 WaitForSingleObject (data->new_sem, INFINITE);
850 if (data->newpfd == NULL)
851 data->newpfd = g_new0 (mono_pollfd, 1);
853 EnterCriticalSection (&data->io_lock);
854 /* FIXME: 64 bit issue: handle can be a pointer on windows? */
855 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
857 list = mono_mlist_alloc ((MonoObject*)state);
859 list = mono_mlist_append (list, (MonoObject*)state);
862 events = get_events_from_list (list);
863 INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
864 mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
865 LeaveCriticalSection (&data->io_lock);
866 *msg = (char) state->operation;
867 #ifndef PLATFORM_WIN32
868 w = write (data->pipe [1], msg, 1);
871 send ((SOCKET) data->pipe [1], msg, 1, 0);
877 socket_io_add_epoll (MonoSocketAsyncResult *state)
880 SocketIOData *data = &socket_io_data;
881 struct epoll_event event;
885 memset (&event, 0, sizeof (struct epoll_event));
886 fd = GPOINTER_TO_INT (state->handle);
887 EnterCriticalSection (&data->io_lock);
888 list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
890 list = mono_mlist_alloc ((MonoObject*)state);
891 epoll_op = EPOLL_CTL_ADD;
893 list = mono_mlist_append (list, (MonoObject*)state);
894 epoll_op = EPOLL_CTL_MOD;
897 ievt = get_events_from_list (list);
898 if ((ievt & MONO_POLLIN) != 0)
899 event.events |= EPOLLIN;
900 if ((ievt & MONO_POLLOUT) != 0)
901 event.events |= EPOLLOUT;
903 mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
906 g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
908 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
910 if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
911 epoll_op = EPOLL_CTL_MOD;
912 if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
913 g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
918 LeaveCriticalSection (&data->io_lock);
924 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
926 socket_io_init (&socket_io_data);
927 MONO_OBJECT_SETREF (state, ares, ares);
929 if (socket_io_data.epoll_disabled == FALSE) {
930 if (socket_io_add_epoll (state))
934 socket_io_add_poll (state);
938 socket_io_filter (MonoObject *target, MonoObject *state)
941 MonoSocketAsyncResult *sock_res = (MonoSocketAsyncResult *) state;
944 if (target == NULL || state == NULL)
947 if (socket_async_call_klass == NULL) {
948 klass = target->vtable->klass;
949 /* Check if it's SocketAsyncCall in System.Net.Sockets
950 * FIXME: check the assembly is signed correctly for extra care
952 if (klass->name [0] == 'S' && strcmp (klass->name, "SocketAsyncCall") == 0
953 && strcmp (mono_image_get_name (klass->image), "System") == 0
954 && klass->nested_in && strcmp (klass->nested_in->name, "Socket") == 0)
955 socket_async_call_klass = klass;
958 if (process_async_call_klass == NULL) {
959 klass = target->vtable->klass;
960 /* Check if it's AsyncReadHandler in System.Diagnostics.Process
961 * FIXME: check the assembly is signed correctly for extra care
963 if (klass->name [0] == 'A' && strcmp (klass->name, "AsyncReadHandler") == 0
964 && strcmp (mono_image_get_name (klass->image), "System") == 0
965 && klass->nested_in && strcmp (klass->nested_in->name, "Process") == 0)
966 process_async_call_klass = klass;
968 /* return both when socket_async_call_klass has not been seen yet and when
969 * the object is not an instance of the class.
971 if (target->vtable->klass != socket_async_call_klass && target->vtable->klass != process_async_call_klass)
974 op = sock_res->operation;
975 if (op < AIO_OP_FIRST || op >= AIO_OP_LAST)
980 #endif /* !DISABLE_SOCKETS */
983 mono_async_invoke (MonoAsyncResult *ares)
985 ASyncCall *ac = (ASyncCall *)ares->object_data;
986 MonoThread *thread = NULL;
987 MonoObject *res, *exc = NULL;
988 MonoArray *out_args = NULL;
990 if (ares->execution_context) {
991 /* use captured ExecutionContext (if available) */
992 thread = mono_thread_current ();
993 MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
994 mono_thread_set_execution_context (ares->execution_context);
996 ares->original_context = NULL;
1000 res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
1001 MONO_OBJECT_SETREF (ac, res, res);
1002 MONO_OBJECT_SETREF (ac, msg->exc, exc);
1003 MONO_OBJECT_SETREF (ac, out_args, out_args);
1005 ares->completed = 1;
1007 /* call async callback if cb_method != null*/
1008 if (ac->cb_method) {
1009 MonoObject *exc = NULL;
1011 mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
1012 /* 'exc' will be the previous ac->msg->exc if not NULL and not
1013 * catched. If catched, this will be set to NULL and the
1014 * exception will not be printed. */
1015 MONO_OBJECT_SETREF (ac->msg, exc, exc);
1018 /* restore original thread execution context if flow isn't suppressed, i.e. non null */
1019 if (ares->original_context) {
1020 mono_thread_set_execution_context (ares->original_context);
1021 ares->original_context = NULL;
1024 /* notify listeners */
1025 mono_monitor_enter ((MonoObject *) ares);
1026 if (ares->handle != NULL) {
1027 ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
1028 SetEvent ((gpointer)(gsize)ac->wait_event);
1030 mono_monitor_exit ((MonoObject *) ares);
1032 EnterCriticalSection (&ares_lock);
1033 mono_g_hash_table_remove (ares_htable, ares);
1034 LeaveCriticalSection (&ares_lock);
1038 start_idle_threads (MonoAsyncResult *data)
1043 needed = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1045 existing = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1046 if ((needed - existing) > 0) {
1047 start_tpthread (data);
1049 threadpool_jobs_dec ((MonoObject*)data);
1051 SleepEx (500, TRUE);
1053 } while ((needed - existing) > 0);
1055 /* If we don't start any thread here, make sure 'data' is processed. */
1057 start_thread_or_queue (data);
1058 threadpool_jobs_dec ((MonoObject*)data);
1063 start_tpthread (MonoAsyncResult *data)
1065 InterlockedIncrement (&mono_worker_threads);
1066 InterlockedIncrement (&busy_worker_threads);
1067 threadpool_jobs_inc ((MonoObject *)data);
1068 mono_thread_create_internal (mono_get_root_domain (), async_invoke_thread, data, TRUE);
1072 mono_thread_pool_init ()
1074 int threads_per_cpu = THREADS_PER_CPU;
1077 if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
1080 MONO_GC_REGISTER_ROOT (ares_htable);
1081 MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
1082 InitializeCriticalSection (&socket_io_data.io_lock);
1083 InitializeCriticalSection (&ares_lock);
1084 InitializeCriticalSection (&io_queue_lock);
1085 ares_htable = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_VALUE_GC);
1086 job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1087 g_assert (job_added != NULL);
1088 if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
1089 threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
1090 if (threads_per_cpu <= 0)
1091 threads_per_cpu = THREADS_PER_CPU;
1094 cpu_count = mono_cpu_count ();
1095 mono_max_worker_threads = 20 + threads_per_cpu * cpu_count;
1096 mono_min_worker_threads = cpu_count; /* 1 idle thread per cpu */
1098 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1099 g_assert (async_call_klass);
1103 mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
1106 MonoDomain *domain = mono_domain_get ();
1107 MonoAsyncResult *ares;
1110 ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
1111 MONO_OBJECT_SETREF (ac, msg, msg);
1112 MONO_OBJECT_SETREF (ac, state, state);
1114 if (async_callback) {
1115 ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
1116 MONO_OBJECT_SETREF (ac, cb_target, async_callback);
1119 ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
1120 MONO_OBJECT_SETREF (ares, async_delegate, target);
1122 EnterCriticalSection (&ares_lock);
1123 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
1124 LeaveCriticalSection (&ares_lock);
1127 mono_g_hash_table_insert (ares_htable, ares, ares);
1128 LeaveCriticalSection (&ares_lock);
1130 #ifndef DISABLE_SOCKETS
1131 if (socket_io_filter (target, state)) {
1132 socket_io_add (ares, (MonoSocketAsyncResult *) state);
1137 start_thread_or_queue (ares);
1142 start_thread_or_queue (MonoAsyncResult *ares)
1146 if ((int) InterlockedCompareExchange (&tp_idle_started, 1, 0) == 0) {
1147 threadpool_jobs_inc ((MonoObject*)ares);
1148 mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, ares, TRUE);
1152 busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1153 worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1154 if (worker <= ++busy &&
1155 worker < mono_max_worker_threads) {
1156 start_tpthread (ares);
1158 append_job (&mono_delegate_section, &async_call_queue, (MonoObject*)ares);
1159 ReleaseSemaphore (job_added, 1, NULL);
1164 mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1171 /* check if already finished */
1172 mono_monitor_enter ((MonoObject *) ares);
1174 if (ares->endinvoke_called) {
1175 *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System",
1176 "InvalidOperationException");
1177 mono_monitor_exit ((MonoObject *) ares);
1181 ares->endinvoke_called = 1;
1182 ac = (ASyncCall *)ares->object_data;
1184 g_assert (ac != NULL);
1186 /* wait until we are really finished */
1187 if (!ares->completed) {
1188 if (ares->handle == NULL) {
1189 ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
1190 g_assert(ac->wait_event != 0);
1191 MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
1193 mono_monitor_exit ((MonoObject *) ares);
1194 WaitForSingleObjectEx ((gpointer)(gsize)ac->wait_event, INFINITE, TRUE);
1196 mono_monitor_exit ((MonoObject *) ares);
1199 *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1200 *out_args = ac->out_args;
1206 mono_thread_pool_cleanup (void)
1210 EnterCriticalSection (&mono_delegate_section);
1211 free_queue (&async_call_queue);
1212 release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1213 LeaveCriticalSection (&mono_delegate_section);
1215 ReleaseSemaphore (job_added, release, NULL);
1217 socket_io_cleanup (&socket_io_data);
1221 null_array (MonoArray *a, int first, int last)
1223 /* We must null the old array because it might
1224 contain cross-appdomain references, which
1225 will crash the GC when the domains are
1227 memset (mono_array_addr (a, MonoObject*, first), 0, sizeof (MonoObject*) * (last - first));
1231 append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar)
1233 threadpool_jobs_inc (ar);
1235 EnterCriticalSection (cs);
1236 if (ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADING ||
1237 ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADED) {
1238 LeaveCriticalSection (cs);
1241 if (list->array && (list->next_elem < mono_array_length (list->array))) {
1242 mono_array_setref (list->array, list->next_elem, ar);
1244 LeaveCriticalSection (cs);
1248 MONO_GC_REGISTER_ROOT (list->array);
1249 list->array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, INITIAL_QUEUE_LENGTH);
1251 int count = list->next_elem - list->first_elem;
1252 /* slide the array or create a larger one if it's full */
1253 if (list->first_elem) {
1254 mono_array_memcpy_refs (list->array, 0, list->array, list->first_elem, count);
1255 null_array (list->array, count, list->next_elem);
1257 MonoArray *olda = list->array;
1258 MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) * 2);
1259 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1261 null_array (olda, list->first_elem, list->next_elem);
1263 list->first_elem = 0;
1264 list->next_elem = count;
1266 mono_array_setref (list->array, list->next_elem, ar);
1268 LeaveCriticalSection (cs);
1273 clear_queue (CRITICAL_SECTION *cs, TPQueue *list, MonoDomain *domain)
1276 EnterCriticalSection (cs);
1278 for (i = list->first_elem; i < list->next_elem; ++i) {
1279 MonoObject *obj = mono_array_get (list->array, MonoObject*, i);
1280 if (obj->vtable->domain == domain) {
1281 unregister_job ((MonoAsyncResult*)obj);
1283 mono_array_set (list->array, MonoObject*, i, NULL);
1284 InterlockedDecrement (&domain->threadpool_jobs);
1291 for (i = list->first_elem; i < list->next_elem; ++i) {
1292 MonoObject *obj = mono_array_get (list->array, MonoObject*, i);
1294 mono_array_set (list->array, MonoObject*, idx++, obj);
1296 list->first_elem = 0;
1297 list->next_elem = count;
1299 LeaveCriticalSection (cs);
1302 static GSList *clear_ares_htable_entries = NULL;
1305 check_ares_htable_entry_for_domain (gpointer key, gpointer value, gpointer user_data)
1307 MonoObject *obj = key;
1308 MonoDomain *domain = user_data;
1310 g_assert (key == value);
1311 if (obj->vtable->domain == domain)
1312 clear_ares_htable_entries = g_slist_prepend (clear_ares_htable_entries, obj);
1316 * Clean up the threadpool of all domain jobs.
1317 * Can only be called as part of the domain unloading process as
1318 * it will wait for all jobs to be visible to the interruption code.
1321 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
1325 guint32 start_time = 0;
1328 g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
1330 clear_queue (&mono_delegate_section, &async_call_queue, domain);
1331 clear_queue (&io_queue_lock, &async_io_queue, domain);
1334 * There might be some threads out that could be about to execute stuff from the given domain.
1335 * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1337 sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
1339 domain->cleanup_semaphore = sem_handle;
1341 * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1342 * and reading threadpool_jobs.
1343 * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
1345 mono_memory_write_barrier ();
1347 if (domain->threadpool_jobs && timeout != -1)
1348 start_time = mono_msec_ticks ();
1349 while (domain->threadpool_jobs) {
1350 WaitForSingleObject (sem_handle, timeout);
1351 if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
1357 domain->cleanup_semaphore = NULL;
1358 CloseHandle (sem_handle);
1360 EnterCriticalSection (&ares_lock);
1361 g_assert (!clear_ares_htable_entries);
1362 mono_g_hash_table_foreach (ares_htable, check_ares_htable_entry_for_domain, domain);
1363 for (list = clear_ares_htable_entries; list; list = list->next)
1364 mono_g_hash_table_remove (ares_htable, list->data);
1365 g_slist_free (clear_ares_htable_entries);
1366 clear_ares_htable_entries = NULL;
1367 LeaveCriticalSection (&ares_lock);
1374 dequeue_job (CRITICAL_SECTION *cs, TPQueue *list)
1379 EnterCriticalSection (cs);
1380 if (!list->array || list->first_elem == list->next_elem) {
1381 LeaveCriticalSection (cs);
1384 ar = mono_array_get (list->array, MonoObject*, list->first_elem);
1385 mono_array_setref (list->array, list->first_elem, NULL);
1387 count = list->next_elem - list->first_elem;
1388 /* reduce the size of the array if it's mostly empty */
1389 if (mono_array_length (list->array) > INITIAL_QUEUE_LENGTH && count < (mono_array_length (list->array) / 3)) {
1390 MonoArray *olda = list->array;
1391 MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) / 2);
1392 mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
1394 null_array (olda, list->first_elem, list->next_elem);
1395 list->first_elem = 0;
1396 list->next_elem = count;
1398 LeaveCriticalSection (cs);
1404 free_queue (TPQueue *list)
1407 null_array (list->array, list->first_elem, list->next_elem);
1409 list->first_elem = list->next_elem = 0;
1413 async_invoke_thread (gpointer data)
1418 const gchar *version;
1420 thread = mono_thread_current ();
1421 version = mono_get_runtime_info ()->framework_version;
1423 MonoAsyncResult *ar;
1425 ar = (MonoAsyncResult *) data;
1427 /* worker threads invokes methods in different domains,
1428 * so we need to set the right domain here */
1429 domain = ((MonoObject *)ar)->vtable->domain;
1433 if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
1434 threadpool_jobs_dec ((MonoObject *)ar);
1435 unregister_job (ar);
1438 mono_thread_push_appdomain_ref (domain);
1439 if (threadpool_jobs_dec ((MonoObject *)ar)) {
1440 unregister_job (ar);
1442 mono_thread_pop_appdomain_ref ();
1446 if (mono_domain_set (domain, FALSE)) {
1449 mono_async_invoke (ar);
1450 ac = (ASyncCall *) ar->object_data;
1452 if (ac->msg->exc != NULL)
1453 mono_unhandled_exception (ac->msg->exc);
1455 mono_domain_set (mono_get_root_domain (), TRUE);
1457 mono_thread_pop_appdomain_ref ();
1458 InterlockedDecrement (&busy_worker_threads);
1459 /* If the callee changes the background status, set it back to TRUE */
1460 if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
1461 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
1465 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1469 int timeout = THREAD_EXIT_TIMEOUT;
1470 guint32 start_time = mono_msec_ticks ();
1473 wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
1474 if (THREAD_WANTS_A_BREAK (thread))
1475 mono_thread_interruption_checkpoint ();
1477 timeout -= mono_msec_ticks () - start_time;
1479 if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION)
1480 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1482 while (!data && timeout > 0);
1486 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1487 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1489 while (!data && workers <= min) {
1490 WaitForSingleObjectEx (job_added, INFINITE, TRUE);
1491 if (THREAD_WANTS_A_BREAK (thread))
1492 mono_thread_interruption_checkpoint ();
1494 data = dequeue_job (&mono_delegate_section, &async_call_queue);
1495 workers = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
1496 min = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1501 InterlockedDecrement (&mono_worker_threads);
1505 InterlockedIncrement (&busy_worker_threads);
1508 g_assert_not_reached ();
1512 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
1516 MONO_ARCH_SAVE_REGS;
1518 busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
1519 busy_io = (gint) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
1520 *workerThreads = mono_max_worker_threads - busy;
1521 *completionPortThreads = mono_io_max_worker_threads - busy_io;
1525 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
1527 MONO_ARCH_SAVE_REGS;
1529 *workerThreads = mono_max_worker_threads;
1530 *completionPortThreads = mono_io_max_worker_threads;
1534 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
1536 gint workers, workers_io;
1538 MONO_ARCH_SAVE_REGS;
1540 workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
1541 workers_io = (gint) InterlockedCompareExchange (&mono_io_min_worker_threads, 0, -1);
1543 *workerThreads = workers;
1544 *completionPortThreads = workers_io;
1548 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
1550 MONO_ARCH_SAVE_REGS;
1552 if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
1555 if (completionPortThreads < 0 || completionPortThreads > mono_io_max_worker_threads)
1558 InterlockedExchange (&mono_min_worker_threads, workerThreads);
1559 InterlockedExchange (&mono_io_min_worker_threads, completionPortThreads);
1560 mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, NULL, TRUE);
1565 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
1567 MONO_ARCH_SAVE_REGS;
1569 if (workerThreads < mono_max_worker_threads)
1572 if (completionPortThreads < mono_io_max_worker_threads)
1575 InterlockedExchange (&mono_max_worker_threads, workerThreads);
1576 InterlockedExchange (&mono_io_max_worker_threads, completionPortThreads);