2009-07-30 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / metadata / threadpool.c
index 612090b0cececef2c8c028a705563c1d325f1cda..4bc6db7340703b4560481c0c0e3ce0c9114661ed 100644 (file)
@@ -5,19 +5,15 @@
  *   Dietmar Maurer (dietmar@ximian.com)
  *   Gonzalo Paniagua Javier (gonzalo@ximian.com)
  *
- * (C) 2001-2003 Ximian, Inc.
- * (c) 2004,2005 Novell, Inc. (http://www.novell.com)
+ * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+ * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
  */
 
 #include <config.h>
 #include <glib.h>
 
-#ifdef PLATFORM_WIN32
-#define WINVER 0x0500
-#define _WIN32_WINNT 0x0500
-#endif
-
-#define THREADS_PER_CPU        5 /* 20 + THREADS_PER_CPU * number of CPUs */
+#define THREADS_PER_CPU        10 /* 20 + THREADS_PER_CPU * number of CPUs */
+#define THREAD_EXIT_TIMEOUT 1000
 
 #include <mono/metadata/domain-internals.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/exception.h>
 #include <mono/metadata/file-io.h>
 #include <mono/metadata/monitor.h>
+#include <mono/metadata/mono-mlist.h>
 #include <mono/metadata/marshal.h>
 #include <mono/metadata/socket-io.h>
 #include <mono/io-layer/io-layer.h>
-#include <mono/os/gc_wrapper.h>
+#include <mono/metadata/gc-internal.h>
+#include <mono/utils/mono-time.h>
+#include <mono/utils/mono-proclib.h>
 #include <errno.h>
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
 #include <sys/types.h>
 #include <fcntl.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <string.h>
-
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
 #include <mono/utils/mono-poll.h>
 #ifdef HAVE_EPOLL
 #include <sys/epoll.h>
 #endif
 
+#ifndef DISABLE_SOCKETS
 #include "mono/io-layer/socket-wrappers.h"
+#endif
 
 #include "threadpool.h"
 
@@ -56,6 +63,7 @@
 static int mono_max_worker_threads;
 static int mono_min_worker_threads;
 static int mono_io_max_worker_threads;
+static int mono_io_min_worker_threads;
 
 /* current number of worker threads */
 static int mono_worker_threads = 0;
@@ -67,6 +75,9 @@ static int busy_io_worker_threads;
 
 /* mono_thread_pool_init called */
 static int tp_inited;
+/* started idle threads */
+static int tp_idle_started;
+
 
 /* we use this to store a reference to the AsyncResult to avoid GC */
 static MonoGHashTable *ares_htable = NULL;
@@ -79,7 +90,7 @@ typedef struct {
        CRITICAL_SECTION io_lock; /* access to sock_to_state */
        int inited;
        int pipe [2];
-       GHashTable *sock_to_state;
+       MonoGHashTable *sock_to_state;
 
        HANDLE new_sem; /* access to newpfd and write side of the pipe */
        mono_pollfd *newpfd;
@@ -108,14 +119,22 @@ typedef struct {
        guint64           wait_event;
 } ASyncCall;
 
+typedef struct {
+       MonoArray *array;
+       int first_elem;
+       int next_elem;
+} TPQueue;
+
 static void async_invoke_thread (gpointer data);
-static void append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar);
+static void append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar);
 static void start_thread_or_queue (MonoAsyncResult *ares);
+static void start_tpthread (MonoAsyncResult *ares);
 static void mono_async_invoke (MonoAsyncResult *ares);
-static gpointer dequeue_job (CRITICAL_SECTION *cs, GList **plist);
+static MonoObject* dequeue_job (CRITICAL_SECTION *cs, TPQueue *list);
+static void free_queue (TPQueue *list);
 
-static GList *async_call_queue = NULL;
-static GList *async_io_queue = NULL;
+static TPQueue async_call_queue = {NULL, 0, 0};
+static TPQueue async_io_queue = {NULL, 0, 0};
 
 static MonoClass *async_call_klass;
 static MonoClass *socket_async_call_klass;
@@ -136,6 +155,9 @@ enum {
        AIO_OP_LAST
 };
 
+#ifdef DISABLE_SOCKETS
+#define socket_io_cleanup(x)
+#else
 static void
 socket_io_cleanup (SocketIOData *data)
 {
@@ -158,10 +180,9 @@ socket_io_cleanup (SocketIOData *data)
        if (data->new_sem)
                CloseHandle (data->new_sem);
        data->new_sem = NULL;
-       g_hash_table_destroy (data->sock_to_state);
+       mono_g_hash_table_destroy (data->sock_to_state);
        data->sock_to_state = NULL;
-       g_list_free (async_io_queue);
-       async_io_queue = NULL;
+       free_queue (&async_io_queue);
        release = (gint) InterlockedCompareExchange (&io_worker_threads, 0, -1);
        if (io_job_added)
                ReleaseSemaphore (io_job_added, release, NULL);
@@ -196,37 +217,67 @@ get_event_from_state (MonoSocketAsyncResult *state)
 }
 
 static int
-get_events_from_list (GSList *list)
+get_events_from_list (MonoMList *list)
 {
        MonoSocketAsyncResult *state;
        int events = 0;
 
-       while (list && list->data) {
-               state = (MonoSocketAsyncResult *) list->data;
+       while (list && (state = (MonoSocketAsyncResult *)mono_mlist_get_data (list))) {
                events |= get_event_from_state (state);
-               list = list->next;
+               list = mono_mlist_next (list);
        }
 
        return events;
 }
 
 #define ICALL_RECV(x)  ves_icall_System_Net_Sockets_Socket_Receive_internal (\
-                               (SOCKET) x->handle, x->buffer, x->offset, x->size,\
+                               (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
                                 x->socket_flags, &x->error);
 
 #define ICALL_SEND(x)  ves_icall_System_Net_Sockets_Socket_Send_internal (\
-                               (SOCKET) x->handle, x->buffer, x->offset, x->size,\
+                               (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
                                 x->socket_flags, &x->error);
 
+#endif /* !DISABLE_SOCKETS */
+
+static void
+unregister_job (MonoAsyncResult *obj)
+{
+       EnterCriticalSection (&ares_lock);
+       mono_g_hash_table_remove (ares_htable, obj);
+       LeaveCriticalSection (&ares_lock);      
+}
+
+static void
+threadpool_jobs_inc (MonoObject *obj)
+{
+       if (obj)
+               InterlockedIncrement (&obj->vtable->domain->threadpool_jobs);
+}
+
+static gboolean
+threadpool_jobs_dec (MonoObject *obj)
+{
+       MonoDomain *domain = obj->vtable->domain;
+       int remaining_jobs = InterlockedDecrement (&domain->threadpool_jobs);
+       if (remaining_jobs == 0 && domain->cleanup_semaphore) {
+               ReleaseSemaphore (domain->cleanup_semaphore, 1, NULL);
+               return TRUE;
+       }
+       return FALSE;
+}
+
+#ifndef DISABLE_SOCKETS
 static void
 async_invoke_io_thread (gpointer data)
 {
        MonoDomain *domain;
        MonoThread *thread;
+       const gchar *version;
+
        thread = mono_thread_current ();
-       thread->threadpool_thread = TRUE;
-       ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
 
+       version = mono_get_runtime_info ()->framework_version;
        for (;;) {
                MonoSocketAsyncResult *state;
                MonoAsyncResult *ar;
@@ -247,37 +298,55 @@ async_invoke_io_thread (gpointer data)
                        /* worker threads invokes methods in different domains,
                         * so we need to set the right domain here */
                        domain = ((MonoObject *)ar)->vtable->domain;
-                       mono_thread_push_appdomain_ref (domain);
-                       if (mono_domain_set (domain, FALSE)) {
-                               ASyncCall *ac;
-
-                               mono_async_invoke (ar);
-                               ac = (ASyncCall *) ar->object_data;
-                               /*
-                               if (ac->msg->exc != NULL)
-                                       mono_unhandled_exception (ac->msg->exc);
-                               */
-                               mono_domain_set (mono_get_root_domain (), TRUE);
+
+                       g_assert (domain);
+
+                       if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
+                               threadpool_jobs_dec ((MonoObject *)ar);
+                               unregister_job (ar);
+                               data = NULL;
+                       } else {
+                               mono_thread_push_appdomain_ref (domain);
+                               if (threadpool_jobs_dec ((MonoObject *)ar)) {
+                                       unregister_job (ar);
+                                       data = NULL;
+                                       mono_thread_pop_appdomain_ref ();
+                                       continue;
+                               }
+                               if (mono_domain_set (domain, FALSE)) {
+                                       ASyncCall *ac;
+
+                                       mono_async_invoke (ar);
+                                       ac = (ASyncCall *) ar->object_data;
+                                       /*
+                                       if (ac->msg->exc != NULL)
+                                               mono_unhandled_exception (ac->msg->exc);
+                                       */
+                                       mono_domain_set (mono_get_root_domain (), TRUE);
+                               }
+                               mono_thread_pop_appdomain_ref ();
+                               InterlockedDecrement (&busy_io_worker_threads);
+                               /* If the callee changes the background status, set it back to TRUE */
+                               if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
+                                       ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
                        }
-                       mono_thread_pop_appdomain_ref ();
-                       InterlockedDecrement (&busy_io_worker_threads);
                }
 
                data = dequeue_job (&io_queue_lock, &async_io_queue);
        
                if (!data) {
                        guint32 wr;
-                       int timeout = 10000;
-                       guint32 start_time = GetTickCount ();
+                       int timeout = THREAD_EXIT_TIMEOUT;
+                       guint32 start_time = mono_msec_ticks ();
                        
                        do {
                                wr = WaitForSingleObjectEx (io_job_added, (guint32)timeout, TRUE);
                                if (THREAD_WANTS_A_BREAK (thread))
                                        mono_thread_interruption_checkpoint ();
                        
-                               timeout -= GetTickCount () - start_time;
+                               timeout -= mono_msec_ticks () - start_time;
                        
-                               if (wr != WAIT_TIMEOUT)
+                               if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION)
                                        data = dequeue_job (&io_queue_lock, &async_io_queue);
                        }
                        while (!data && timeout > 0);
@@ -304,7 +373,6 @@ static void
 start_io_thread_or_queue (MonoSocketAsyncResult *ares)
 {
        int busy, worker;
-       MonoDomain *domain;
 
        busy = (int) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
        worker = (int) InterlockedCompareExchange (&io_worker_threads, 0, -1); 
@@ -312,33 +380,32 @@ start_io_thread_or_queue (MonoSocketAsyncResult *ares)
            worker < mono_io_max_worker_threads) {
                InterlockedIncrement (&busy_io_worker_threads);
                InterlockedIncrement (&io_worker_threads);
-               domain = ((ares) ? ((MonoObject *) ares)->vtable->domain : mono_domain_get ());
-               mono_thread_create (mono_get_root_domain (), async_invoke_io_thread, ares);
+               threadpool_jobs_inc ((MonoObject *)ares);
+               mono_thread_create_internal (mono_get_root_domain (), async_invoke_io_thread, ares, TRUE);
        } else {
-               append_job (&io_queue_lock, &async_io_queue, ares);
+               append_job (&io_queue_lock, &async_io_queue, (MonoObject*)ares);
                ReleaseSemaphore (io_job_added, 1, NULL);
        }
 }
 
-static GSList *
-process_io_event (GSList *list, int event)
+static MonoMList *
+process_io_event (MonoMList *list, int event)
 {
        MonoSocketAsyncResult *state;
-       GSList *oldlist;
+       MonoMList *oldlist;
 
        oldlist = list;
        state = NULL;
        while (list) {
-               state = (MonoSocketAsyncResult *) list->data;
+               state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
                if (get_event_from_state (state) == event)
                        break;
                
-               list = list->next;
+               list = mono_mlist_next (list);
        }
 
        if (list != NULL) {
-               oldlist = g_slist_remove_link (oldlist, list);
-               g_slist_free_1 (list);
+               oldlist = mono_mlist_remove_item (oldlist, list);
 #ifdef EPOLL_DEBUG
                g_print ("Dispatching event %d on socket %d\n", event, state->handle);
 #endif
@@ -386,8 +453,6 @@ socket_io_poll_main (gpointer p)
        MonoThread *thread;
 
        thread = mono_thread_current ();
-       thread->threadpool_thread = TRUE;
-       ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
 
        allocated = INITIAL_POLLFD_SIZE;
        pfds = g_new0 (mono_pollfd, allocated);
@@ -399,7 +464,7 @@ socket_io_poll_main (gpointer p)
                int nsock = 0;
                mono_pollfd *pfd;
                char one [1];
-               GSList *list;
+               MonoMList *list;
 
                do {
                        if (nsock == -1) {
@@ -480,6 +545,7 @@ socket_io_poll_main (gpointer p)
                EnterCriticalSection (&data->io_lock);
                if (data->inited == 0) {
                        g_free (pfds);
+                       LeaveCriticalSection (&data->io_lock);
                        return; /* cleanup called */
                }
 
@@ -489,7 +555,7 @@ socket_io_poll_main (gpointer p)
                                continue;
 
                        nsock--;
-                       list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
+                       list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
                        if (list != NULL && (pfd->revents & (MONO_POLLIN | POLL_ERRORS)) != 0) {
                                list = process_io_event (list, MONO_POLLIN);
                        }
@@ -499,10 +565,10 @@ socket_io_poll_main (gpointer p)
                        }
 
                        if (list != NULL) {
-                               g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
+                               mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (pfd->fd), list);
                                pfd->events = get_events_from_list (list);
                        } else {
-                               g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
+                               mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (pfd->fd));
                                pfd->fd = -1;
                                if (i == maxfd - 1)
                                        maxfd--;
@@ -527,8 +593,6 @@ socket_io_epoll_main (gpointer p)
        data = p;
        epollfd = data->epollfd;
        thread = mono_thread_current ();
-       thread->threadpool_thread = TRUE;
-       ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
        events = g_new0 (struct epoll_event, nevents);
 
        while (1) {
@@ -572,13 +636,13 @@ socket_io_epoll_main (gpointer p)
 
                for (i = 0; i < ready; i++) {
                        int fd;
-                       GSList *list;
+                       MonoMList *list;
 
                        evt = &events [i];
                        fd = evt->data.fd;
-                       list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
+                       list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
 #ifdef EPOLL_DEBUG
-                       g_print ("Event %d on %d list length: %d\n", evt->events, fd, g_slist_length (list));
+                       g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
 #endif
                        if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
                                list = process_io_event (list, MONO_POLLIN);
@@ -589,7 +653,7 @@ socket_io_epoll_main (gpointer p)
                        }
 
                        if (list != NULL) {
-                               g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
+                               mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
                                evt->events = get_events_from_list (list);
 #ifdef EPOLL_DEBUG
                                g_print ("MOD %d to %d\n", fd, evt->events);
@@ -604,7 +668,7 @@ socket_io_epoll_main (gpointer p)
                                        }
                                }
                        } else {
-                               g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
+                               mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
 #ifdef EPOLL_DEBUG
                                g_print ("DEL %d\n", fd);
 #endif
@@ -623,35 +687,33 @@ socket_io_epoll_main (gpointer p)
 void
 mono_thread_pool_remove_socket (int sock)
 {
-#ifdef HAVE_EPOLL
-       GSList *list, *next;
+       MonoMList *list, *next;
        MonoSocketAsyncResult *state;
 
-       if (socket_io_data.epoll_disabled == TRUE || socket_io_data.inited == FALSE)
+       if (socket_io_data.inited == FALSE)
                return;
 
        EnterCriticalSection (&socket_io_data.io_lock);
-       list = g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
+       list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
        if (list) {
-               g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
+               mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
        }
        LeaveCriticalSection (&socket_io_data.io_lock);
        
        while (list) {
-               state = (MonoSocketAsyncResult *) list->data;
+               state = (MonoSocketAsyncResult *) mono_mlist_get_data (list);
                if (state->operation == AIO_OP_RECEIVE)
                        state->operation = AIO_OP_RECV_JUST_CALLBACK;
                else if (state->operation == AIO_OP_SEND)
                        state->operation = AIO_OP_SEND_JUST_CALLBACK;
 
-               next = g_slist_remove_link (list, list);
+               next = mono_mlist_remove_item (list, list);
                list = process_io_event (list, MONO_POLLIN);
                if (list)
                        process_io_event (list, MONO_POLLOUT);
 
                list = next;
        }
-#endif
 }
 
 #ifdef PLATFORM_WIN32
@@ -745,18 +807,20 @@ socket_io_init (SocketIOData *data)
        if (mono_io_max_worker_threads < 10)
                mono_io_max_worker_threads = 10;
 
-       data->sock_to_state = g_hash_table_new (g_direct_hash, g_direct_equal);
+       data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
 
-       if (data->epoll_disabled)
+       if (data->epoll_disabled) {
                data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
+               g_assert (data->new_sem != NULL);
+       }
        io_job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
-       InitializeCriticalSection (&io_queue_lock);
+       g_assert (io_job_added != NULL);
        if (data->epoll_disabled) {
-               mono_thread_create (mono_get_root_domain (), socket_io_poll_main, data);
+               mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
        }
 #ifdef HAVE_EPOLL
        else {
-               mono_thread_create (mono_get_root_domain (), socket_io_epoll_main, data);
+               mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
        }
 #endif
        InterlockedCompareExchange (&data->inited, 1, 0);
@@ -768,10 +832,10 @@ socket_io_add_poll (MonoSocketAsyncResult *state)
 {
        int events;
        char msg [1];
-       GSList *list;
+       MonoMList *list;
        SocketIOData *data = &socket_io_data;
 
-#if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD6) || defined(PLATFORM_WIN32)
+#if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(PLATFORM_WIN32) || defined(PLATFORM_SOLARIS)
        /* select() for connect() does not work well on the Mac. Bug #75436. */
        /* Bug #77637 for the BSD 6 case */
        /* Bug #78888 for the Windows case */
@@ -785,17 +849,17 @@ socket_io_add_poll (MonoSocketAsyncResult *state)
                data->newpfd = g_new0 (mono_pollfd, 1);
 
        EnterCriticalSection (&data->io_lock);
-       list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
+       /* FIXME: 64 bit issue: handle can be a pointer on windows? */
+       list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
        if (list == NULL) {
-               list = g_slist_alloc ();
-               list->data = state;
+               list = mono_mlist_alloc ((MonoObject*)state);
        } else {
-               list = g_slist_append (list, state);
+               list = mono_mlist_append (list, (MonoObject*)state);
        }
 
        events = get_events_from_list (list);
        INIT_POLLFD (data->newpfd, GPOINTER_TO_INT (state->handle), events);
-       g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
+       mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (state->handle), list);
        LeaveCriticalSection (&data->io_lock);
        *msg = (char) state->operation;
 #ifndef PLATFORM_WIN32
@@ -809,7 +873,7 @@ socket_io_add_poll (MonoSocketAsyncResult *state)
 static gboolean
 socket_io_add_epoll (MonoSocketAsyncResult *state)
 {
-       GSList *list;
+       MonoMList *list;
        SocketIOData *data = &socket_io_data;
        struct epoll_event event;
        int epoll_op, ievt;
@@ -818,13 +882,12 @@ socket_io_add_epoll (MonoSocketAsyncResult *state)
        memset (&event, 0, sizeof (struct epoll_event));
        fd = GPOINTER_TO_INT (state->handle);
        EnterCriticalSection (&data->io_lock);
-       list = g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
+       list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
        if (list == NULL) {
-               list = g_slist_alloc ();
-               list->data = state;
+               list = mono_mlist_alloc ((MonoObject*)state);
                epoll_op = EPOLL_CTL_ADD;
        } else {
-               list = g_slist_append (list, state);
+               list = mono_mlist_append (list, (MonoObject*)state);
                epoll_op = EPOLL_CTL_MOD;
        }
 
@@ -834,7 +897,7 @@ socket_io_add_epoll (MonoSocketAsyncResult *state)
        if ((ievt & MONO_POLLOUT) != 0)
                event.events |= EPOLLOUT;
 
-       g_hash_table_replace (data->sock_to_state, state->handle, list);
+       mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
        event.data.fd = fd;
 #ifdef EPOLL_DEBUG
        g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
@@ -911,25 +974,30 @@ socket_io_filter (MonoObject *target, MonoObject *state)
 
        return TRUE;
 }
+#endif /* !DISABLE_SOCKETS */
 
 static void
 mono_async_invoke (MonoAsyncResult *ares)
 {
        ASyncCall *ac = (ASyncCall *)ares->object_data;
        MonoThread *thread = NULL;
+       MonoObject *res, *exc = NULL;
+       MonoArray *out_args = NULL;
 
        if (ares->execution_context) {
                /* use captured ExecutionContext (if available) */
                thread = mono_thread_current ();
-               MONO_OBJECT_SETREF (ares, original_context, thread->execution_context);
-               MONO_OBJECT_SETREF (thread, execution_context, ares->execution_context);
+               MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
+               mono_thread_set_execution_context (ares->execution_context);
        } else {
                ares->original_context = NULL;
        }
 
        ac->msg->exc = NULL;
-       ac->res = mono_message_invoke (ares->async_delegate, ac->msg, 
-                                      &ac->msg->exc, &ac->out_args);
+       res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
+       MONO_OBJECT_SETREF (ac, res, res);
+       MONO_OBJECT_SETREF (ac, msg->exc, exc);
+       MONO_OBJECT_SETREF (ac, out_args, out_args);
 
        ares->completed = 1;
 
@@ -946,14 +1014,14 @@ mono_async_invoke (MonoAsyncResult *ares)
 
        /* restore original thread execution context if flow isn't suppressed, i.e. non null */
        if (ares->original_context) {
-               MONO_OBJECT_SETREF (thread, execution_context, ares->original_context);
+               mono_thread_set_execution_context (ares->original_context);
                ares->original_context = NULL;
        }
 
        /* notify listeners */
        mono_monitor_enter ((MonoObject *) ares);
        if (ares->handle != NULL) {
-               ac->wait_event = (gsize)((MonoWaitHandle *) ares->handle)->handle;
+               ac->wait_event = (gsize) mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
                SetEvent ((gpointer)(gsize)ac->wait_event);
        }
        mono_monitor_exit ((MonoObject *) ares);
@@ -963,28 +1031,66 @@ mono_async_invoke (MonoAsyncResult *ares)
        LeaveCriticalSection (&ares_lock);
 }
 
+static void
+start_idle_threads (MonoAsyncResult *data)
+{
+       int needed;
+       int existing;
+
+       needed = (int) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1); 
+       do {
+               existing = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
+               if ((needed - existing) > 0) {
+                       start_tpthread (data);
+                       if (data) 
+                               threadpool_jobs_dec ((MonoObject*)data);
+                       data = NULL;
+                       Sleep (500);
+               }
+       } while ((needed - existing) > 0);
+
+       /* If we don't start any thread here, make sure 'data' is processed. */
+       if (data != NULL) {
+               start_thread_or_queue (data);
+               threadpool_jobs_dec ((MonoObject*)data);
+       }
+}
+
+static void
+start_tpthread (MonoAsyncResult *data)
+{
+       InterlockedIncrement (&mono_worker_threads);
+       InterlockedIncrement (&busy_worker_threads);
+       threadpool_jobs_inc ((MonoObject *)data);
+       mono_thread_create_internal (mono_get_root_domain (), async_invoke_thread, data, TRUE);
+}
+
 void
 mono_thread_pool_init ()
 {
-       SYSTEM_INFO info;
        int threads_per_cpu = THREADS_PER_CPU;
+       int cpu_count;
 
        if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
                return;
 
        MONO_GC_REGISTER_ROOT (ares_htable);
+       MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
        InitializeCriticalSection (&socket_io_data.io_lock);
        InitializeCriticalSection (&ares_lock);
+       InitializeCriticalSection (&io_queue_lock);
        ares_htable = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
        job_added = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
-       GetSystemInfo (&info);
+       g_assert (job_added != NULL);
        if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
                threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
                if (threads_per_cpu <= 0)
                        threads_per_cpu = THREADS_PER_CPU;
        }
 
-       mono_max_worker_threads = 20 + threads_per_cpu * info.dwNumberOfProcessors;
+       cpu_count = mono_cpu_count ();
+       mono_max_worker_threads = 20 + threads_per_cpu * cpu_count;
+       mono_min_worker_threads = cpu_count; /* 1 idle thread per cpu */
 
        async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
        g_assert (async_call_klass);
@@ -998,35 +1104,32 @@ mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *
        MonoAsyncResult *ares;
        ASyncCall *ac;
 
-#ifdef HAVE_BOEHM_GC
-       ac = GC_MALLOC (sizeof (ASyncCall));
-#elif defined(HAVE_SGEN_GC)
-       ac = mono_object_new (mono_domain_get (), async_call_klass);
-#else
-       /* We'll leak the event if creaated... */
-       ac = g_new0 (ASyncCall, 1);
-#endif
-       ac->wait_event = 0;
+       ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
        MONO_OBJECT_SETREF (ac, msg, msg);
        MONO_OBJECT_SETREF (ac, state, state);
 
        if (async_callback) {
                ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
-               ac->cb_target = async_callback;
+               MONO_OBJECT_SETREF (ac, cb_target, async_callback);
        }
 
        ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
        MONO_OBJECT_SETREF (ares, async_delegate, target);
 
+       if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING)
+               return ares;
+
        EnterCriticalSection (&ares_lock);
        mono_g_hash_table_insert (ares_htable, ares, ares);
        LeaveCriticalSection (&ares_lock);
 
+#ifndef DISABLE_SOCKETS
        if (socket_io_filter (target, state)) {
                socket_io_add (ares, (MonoSocketAsyncResult *) state);
                return ares;
        }
-
+#endif
+       
        start_thread_or_queue (ares);
        return ares;
 }
@@ -1036,15 +1139,19 @@ start_thread_or_queue (MonoAsyncResult *ares)
 {
        int busy, worker;
 
+       if ((int) InterlockedCompareExchange (&tp_idle_started, 1, 0) == 0) {
+               threadpool_jobs_inc ((MonoObject*)ares);
+               mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, ares, TRUE);
+               return;
+       }
+
        busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
        worker = (int) InterlockedCompareExchange (&mono_worker_threads, 0, -1); 
        if (worker <= ++busy &&
            worker < mono_max_worker_threads) {
-               InterlockedIncrement (&mono_worker_threads);
-               InterlockedIncrement (&busy_worker_threads);
-               mono_thread_create (mono_get_root_domain (), async_invoke_thread, ares);
+               start_tpthread (ares);
        } else {
-               append_job (&mono_delegate_section, &async_call_queue, ares);
+               append_job (&mono_delegate_section, &async_call_queue, (MonoObject*)ares);
                ReleaseSemaphore (job_added, 1, NULL);
        }
 }
@@ -1076,6 +1183,7 @@ mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject
        if (!ares->completed) {
                if (ares->handle == NULL) {
                        ac->wait_event = (gsize)CreateEvent (NULL, TRUE, FALSE, NULL);
+                       g_assert(ac->wait_event != 0);
                        MONO_OBJECT_SETREF (ares, handle, (MonoObject *) mono_wait_handle_new (mono_object_domain (ares), (gpointer)(gsize)ac->wait_event));
                }
                mono_monitor_exit ((MonoObject *) ares);
@@ -1096,8 +1204,7 @@ mono_thread_pool_cleanup (void)
        gint release;
 
        EnterCriticalSection (&mono_delegate_section);
-       g_list_free (async_call_queue);
-       async_call_queue = NULL;
+       free_queue (&async_call_queue);
        release = (gint) InterlockedCompareExchange (&mono_worker_threads, 0, -1);
        LeaveCriticalSection (&mono_delegate_section);
        if (job_added)
@@ -1107,64 +1214,159 @@ mono_thread_pool_cleanup (void)
 }
 
 static void
-append_job (CRITICAL_SECTION *cs, GList **plist, gpointer ar)
+append_job (CRITICAL_SECTION *cs, TPQueue *list, MonoObject *ar)
 {
-       GList *tmp, *list;
+       threadpool_jobs_inc (ar); 
 
        EnterCriticalSection (cs);
-       list = *plist;
-       if (list == NULL) {
-               list = g_list_append (list, ar); 
+       if (list->array && (list->next_elem < mono_array_length (list->array))) {
+               mono_array_setref (list->array, list->next_elem, ar);
+               list->next_elem++;
+               LeaveCriticalSection (cs);
+               return;
+       }
+       if (!list->array) {
+               MONO_GC_REGISTER_ROOT (list->array);
+               list->array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, 16);
        } else {
-               for (tmp = list; tmp && tmp->data != NULL; tmp = tmp->next);
-               if (tmp == NULL) {
-                       list = g_list_append (list, ar); 
+               int count = list->next_elem - list->first_elem;
+               /* slide the array or create a larger one if it's full */
+               if (list->first_elem) {
+                       mono_array_memcpy_refs (list->array, 0, list->array, list->first_elem, count);
                } else {
-                       tmp->data = ar;
+                       MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) * 2);
+                       mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
+                       list->array = newa;
                }
+               list->first_elem = 0;
+               list->next_elem = count;
        }
-       *plist = list;
+       mono_array_setref (list->array, list->next_elem, ar);
+       list->next_elem++;
        LeaveCriticalSection (cs);
 }
 
-static gpointer
-dequeue_job (CRITICAL_SECTION *cs, GList **plist)
-{
-       gpointer ar = NULL;
-       GList *tmp, *tmp2, *list;
 
+static void
+clear_queue (CRITICAL_SECTION *cs, TPQueue *list, MonoDomain *domain)
+{
+       int i, count = 0;
        EnterCriticalSection (cs);
-       list = *plist;
-       tmp = list;
-       if (tmp) {
-               ar = tmp->data;
-               tmp->data = NULL;
-               tmp2 = tmp;
-               for (tmp2 = tmp; tmp2->next != NULL; tmp2 = tmp2->next);
-               if (tmp2 != tmp) {
-                       list = tmp->next;
-                       tmp->next = NULL;
-                       tmp2->next = tmp;
-                       tmp->prev = tmp2;
+       /*remove*/
+       for (i = list->first_elem; i < list->next_elem; ++i) {
+               MonoObject *obj = mono_array_get (list->array, MonoObject*, i);
+               if (obj->vtable->domain == domain) {
+                       unregister_job ((MonoAsyncResult*)obj);
+
+                       mono_array_set (list->array, MonoObject*, i, NULL);
+                       InterlockedDecrement (&domain->threadpool_jobs);
+                       ++count;
+               }
+       }
+       /*compact*/
+       if (count) {
+               int idx = 0;
+               for (i = list->first_elem; i < list->next_elem; ++i) {
+                       MonoObject *obj = mono_array_get (list->array, MonoObject*, i);
+                       if (obj)
+                               mono_array_set (list->array, MonoObject*, idx++, obj);
                }
+               list->first_elem = 0;
+               list->next_elem = count;
+       }
+       LeaveCriticalSection (cs);
+}
+
+/*
+ * Clean up the threadpool of all domain jobs.
+ * Can only be called as part of the domain unloading process as
+ * it will wait for all jobs to be visible to the interruption code. 
+ */
+gboolean
+mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
+{
+       HANDLE sem_handle;
+       int result = TRUE;
+       guint32 start_time = 0;
+
+       clear_queue (&mono_delegate_section, &async_call_queue, domain);
+       clear_queue (&io_queue_lock, &async_io_queue, domain);
+
+       /*
+        * There might be some threads out that could be about to execute stuff from the given domain.
+        * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
+        */
+       sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
+       
+       domain->cleanup_semaphore = sem_handle;
+       /*
+        * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
+        * and reading threadpool_jobs.
+        * Otherwise this thread could read a stale version of threadpool_jobs and wait forever.
+        */
+       mono_memory_write_barrier ();
+
+       if (domain->threadpool_jobs && timeout != -1)
+               start_time = mono_msec_ticks ();
+       while (domain->threadpool_jobs) {
+               WaitForSingleObject (sem_handle, timeout);
+               if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
+                       result = FALSE;
+                       break;
+               }
+       }
+
+       domain->cleanup_semaphore = NULL;
+       CloseHandle (sem_handle);
+       return result;
+}
+
+
+static MonoObject*
+dequeue_job (CRITICAL_SECTION *cs, TPQueue *list)
+{
+       MonoObject *ar;
+       int count;
+
+       EnterCriticalSection (cs);
+       if (!list->array || list->first_elem == list->next_elem) {
+               LeaveCriticalSection (cs);
+               return NULL;
+       }
+       ar = mono_array_get (list->array, MonoObject*, list->first_elem);
+       mono_array_setref (list->array, list->first_elem, NULL);
+       list->first_elem++;
+       count = list->next_elem - list->first_elem;
+       /* reduce the size of the array if it's mostly empty */
+       if (mono_array_length (list->array) > 16 && count < (mono_array_length (list->array) / 3)) {
+               MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (list->array) / 2);
+               mono_array_memcpy_refs (newa, 0, list->array, list->first_elem, count);
+               list->array = newa;
+               list->first_elem = 0;
+               list->next_elem = count;
        }
-       *plist = list;
        LeaveCriticalSection (cs);
 
        return ar;
 }
 
+static void
+free_queue (TPQueue *list)
+{
+       list->array = NULL;
+       list->first_elem = list->next_elem = 0;
+}
+
 static void
 async_invoke_thread (gpointer data)
 {
        MonoDomain *domain;
        MonoThread *thread;
        int workers, min;
+       const gchar *version;
  
        thread = mono_thread_current ();
-       thread->threadpool_thread = TRUE;
-       ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
-
+       version = mono_get_runtime_info ()->framework_version;
        for (;;) {
                MonoAsyncResult *ar;
 
@@ -1173,37 +1375,56 @@ async_invoke_thread (gpointer data)
                        /* worker threads invokes methods in different domains,
                         * so we need to set the right domain here */
                        domain = ((MonoObject *)ar)->vtable->domain;
-                       mono_thread_push_appdomain_ref (domain);
-                       if (mono_domain_set (domain, FALSE)) {
-                               ASyncCall *ac;
-
-                               mono_async_invoke (ar);
-                               ac = (ASyncCall *) ar->object_data;
-                               /*
-                               if (ac->msg->exc != NULL)
-                                       mono_unhandled_exception (ac->msg->exc);
-                               */
-                               mono_domain_set (mono_get_root_domain (), TRUE);
+
+                       g_assert (domain);
+
+                       if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
+                               threadpool_jobs_dec ((MonoObject *)ar);
+                               unregister_job (ar);
+                               data = NULL;
+                       } else {
+                               mono_thread_push_appdomain_ref (domain);
+                               if (threadpool_jobs_dec ((MonoObject *)ar)) {
+                                       unregister_job (ar);
+                                       data = NULL;
+                                       mono_thread_pop_appdomain_ref ();
+                                       continue;
+                               }
+
+                               if (mono_domain_set (domain, FALSE)) {
+                                       ASyncCall *ac;
+
+                                       mono_async_invoke (ar);
+                                       ac = (ASyncCall *) ar->object_data;
+                                       /*
+                                       if (ac->msg->exc != NULL)
+                                               mono_unhandled_exception (ac->msg->exc);
+                                       */
+                                       mono_domain_set (mono_get_root_domain (), TRUE);
+                               }
+                               mono_thread_pop_appdomain_ref ();
+                               InterlockedDecrement (&busy_worker_threads);
+                               /* If the callee changes the background status, set it back to TRUE */
+                               if (*version != '1' && !mono_thread_test_state (thread , ThreadState_Background))
+                                       ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
                        }
-                       mono_thread_pop_appdomain_ref ();
-                       InterlockedDecrement (&busy_worker_threads);
                }
 
                data = dequeue_job (&mono_delegate_section, &async_call_queue);
 
                if (!data) {
                        guint32 wr;
-                       int timeout = 10000;
-                       guint32 start_time = GetTickCount ();
+                       int timeout = THREAD_EXIT_TIMEOUT;
+                       guint32 start_time = mono_msec_ticks ();
                        
                        do {
                                wr = WaitForSingleObjectEx (job_added, (guint32)timeout, TRUE);
                                if (THREAD_WANTS_A_BREAK (thread))
                                        mono_thread_interruption_checkpoint ();
                        
-                               timeout -= GetTickCount () - start_time;
+                               timeout -= mono_msec_ticks () - start_time;
                        
-                               if (wr != WAIT_TIMEOUT)
+                               if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION)
                                        data = dequeue_job (&mono_delegate_section, &async_call_queue);
                        }
                        while (!data && timeout > 0);
@@ -1238,13 +1459,14 @@ async_invoke_thread (gpointer data)
 void
 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
 {
-       gint busy;
+       gint busy, busy_io;
 
        MONO_ARCH_SAVE_REGS;
 
        busy = (gint) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
+       busy_io = (gint) InterlockedCompareExchange (&busy_io_worker_threads, 0, -1);
        *workerThreads = mono_max_worker_threads - busy;
-       *completionPortThreads = 0;
+       *completionPortThreads = mono_io_max_worker_threads - busy_io;
 }
 
 void
@@ -1253,19 +1475,21 @@ ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *
        MONO_ARCH_SAVE_REGS;
 
        *workerThreads = mono_max_worker_threads;
-       *completionPortThreads = 0;
+       *completionPortThreads = mono_io_max_worker_threads;
 }
 
 void
 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
 {
-       gint workers;
+       gint workers, workers_io;
 
        MONO_ARCH_SAVE_REGS;
 
        workers = (gint) InterlockedCompareExchange (&mono_min_worker_threads, 0, -1);
+       workers_io = (gint) InterlockedCompareExchange (&mono_io_min_worker_threads, 0, -1);
+
        *workerThreads = workers;
-       *completionPortThreads = 0;
+       *completionPortThreads = workers_io;
 }
 
 MonoBoolean
@@ -1275,8 +1499,29 @@ ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint co
 
        if (workerThreads < 0 || workerThreads > mono_max_worker_threads)
                return FALSE;
+
+       if (completionPortThreads < 0 || completionPortThreads > mono_io_max_worker_threads)
+               return FALSE;
+
        InterlockedExchange (&mono_min_worker_threads, workerThreads);
-       /* FIXME: should actually start the idle threads if needed */
+       InterlockedExchange (&mono_io_min_worker_threads, completionPortThreads);
+       mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, NULL, TRUE);
+       return TRUE;
+}
+
+MonoBoolean
+ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
+{
+       MONO_ARCH_SAVE_REGS;
+
+       if (workerThreads < mono_max_worker_threads)
+               return FALSE;
+
+       if (completionPortThreads < mono_io_max_worker_threads)
+               return FALSE;
+
+       InterlockedExchange (&mono_max_worker_threads, workerThreads);
+       InterlockedExchange (&mono_io_max_worker_threads, completionPortThreads);
        return TRUE;
 }