dfd61ea3f589177a1aa7c7f9cd877e85488a6052
[mono.git] / mono / metadata / threadpool.c
1 /*
2  * threadpool.c: Microsoft threadpool runtime support
3  *
4  * Author:
5  *      Ludovic Henry (ludovic.henry@xamarin.com)
6  *
7  * Copyright 2015 Xamarin, Inc (http://www.xamarin.com)
8  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
9  */
10
11 //
12 // Copyright (c) Microsoft. All rights reserved.
13 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 //
15 // Files:
16 //  - src/vm/comthreadpool.cpp
17 //  - src/vm/win32threadpoolcpp
18 //  - src/vm/threadpoolrequest.cpp
19 //  - src/vm/hillclimbing.cpp
20 //
21 // Ported from C++ to C and adjusted to Mono runtime
22
23 #include <stdlib.h>
24 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
25 #include <math.h>
26 #include <config.h>
27 #include <glib.h>
28
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/gc-internals.h>
32 #include <mono/metadata/object.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/metadata/threadpool.h>
35 #include <mono/metadata/threadpool-worker.h>
36 #include <mono/metadata/threadpool-io.h>
37 #include <mono/metadata/w32event.h>
38 #include <mono/utils/atomic.h>
39 #include <mono/utils/mono-compiler.h>
40 #include <mono/utils/mono-complex.h>
41 #include <mono/utils/mono-lazy-init.h>
42 #include <mono/utils/mono-logger.h>
43 #include <mono/utils/mono-logger-internals.h>
44 #include <mono/utils/mono-proclib.h>
45 #include <mono/utils/mono-threads.h>
46 #include <mono/utils/mono-time.h>
47 #include <mono/utils/refcount.h>
48
49 typedef struct {
50         MonoDomain *domain;
51         /* Number of outstanding jobs */
52         gint32 outstanding_request;
53         /* Number of currently executing jobs */
54         gint32 threadpool_jobs;
55         /* Signalled when threadpool_jobs + outstanding_request is 0 */
56         /* Protected by threadpool->domains_lock */
57         MonoCoopCond cleanup_cond;
58 } ThreadPoolDomain;
59
60 typedef union {
61         struct {
62                 gint16 starting; /* starting, but not yet in worker_callback */
63                 gint16 working; /* executing worker_callback */
64         } _;
65         gint32 as_gint32;
66 } ThreadPoolCounter;
67
68 typedef struct {
69         MonoRefCount ref;
70
71         GPtrArray *domains; // ThreadPoolDomain* []
72         MonoCoopMutex domains_lock;
73
74         GPtrArray *threads; // MonoInternalThread* []
75         MonoCoopMutex threads_lock;
76         MonoCoopCond threads_exit_cond;
77
78         ThreadPoolCounter counters;
79
80         gint32 limit_io_min;
81         gint32 limit_io_max;
82
83         MonoThreadPoolWorker *worker;
84 } ThreadPool;
85
86 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
87
88 static ThreadPool* threadpool;
89
90 #define COUNTER_ATOMIC(threadpool,var,block) \
91         do { \
92                 ThreadPoolCounter __old; \
93                 do { \
94                         g_assert (threadpool); \
95                         (var) = __old = COUNTER_READ (threadpool); \
96                         { block; } \
97                         if (!(counter._.starting >= 0)) \
98                                 g_error ("%s: counter._.starting = %d, but should be >= 0", __func__, counter._.starting); \
99                         if (!(counter._.working >= 0)) \
100                                 g_error ("%s: counter._.working = %d, but should be >= 0", __func__, counter._.working); \
101                 } while (InterlockedCompareExchange (&threadpool->counters.as_gint32, (var).as_gint32, __old.as_gint32) != __old.as_gint32); \
102         } while (0)
103
104 static inline ThreadPoolCounter
105 COUNTER_READ (ThreadPool *threadpool)
106 {
107         ThreadPoolCounter counter;
108         counter.as_gint32 = InterlockedRead (&threadpool->counters.as_gint32);
109         return counter;
110 }
111
112 static inline void
113 domains_lock (void)
114 {
115         mono_coop_mutex_lock (&threadpool->domains_lock);
116 }
117
118 static inline void
119 domains_unlock (void)
120 {
121         mono_coop_mutex_unlock (&threadpool->domains_lock);
122 }
123
124 static void
125 destroy (gpointer unused)
126 {
127         g_ptr_array_free (threadpool->domains, TRUE);
128         mono_coop_mutex_destroy (&threadpool->domains_lock);
129
130         g_ptr_array_free (threadpool->threads, TRUE);
131         mono_coop_mutex_destroy (&threadpool->threads_lock);
132         mono_coop_cond_destroy (&threadpool->threads_exit_cond);
133
134         /* We cannot free the threadpool, because there is a race
135          * on shutdown where a managed thread may request a new
136          * threadpool thread, but we already destroyed the
137          * threadpool. So to avoid a use-after-free, we simply do
138          * not free the threadpool, as we won't be able to access
139          * the threadpool anyway because the ref count will be 0 */
140         // g_free (threadpool);
141 }
142
143 static void
144 initialize (void)
145 {
146         g_assert (!threadpool);
147         threadpool = g_new0 (ThreadPool, 1);
148         g_assert (threadpool);
149
150         g_assert (sizeof (ThreadPoolCounter) == sizeof (gint32));
151
152         mono_refcount_init (threadpool, destroy);
153
154         threadpool->domains = g_ptr_array_new ();
155         mono_coop_mutex_init (&threadpool->domains_lock);
156
157         threadpool->threads = g_ptr_array_new ();
158         mono_coop_mutex_init (&threadpool->threads_lock);
159         mono_coop_cond_init (&threadpool->threads_exit_cond);
160
161         threadpool->limit_io_min = mono_cpu_count ();
162         threadpool->limit_io_max = CLAMP (threadpool->limit_io_min * 100, MIN (threadpool->limit_io_min, 200), MAX (threadpool->limit_io_min, 200));
163
164         mono_threadpool_worker_init (&threadpool->worker);
165 }
166
167 static void
168 cleanup (void)
169 {
170         guint i;
171         MonoInternalThread *current;
172
173         /* we make the assumption along the code that we are
174          * cleaning up only if the runtime is shutting down */
175         g_assert (mono_runtime_is_shutting_down ());
176
177         current = mono_thread_internal_current ();
178
179         mono_coop_mutex_lock (&threadpool->threads_lock);
180
181         /* stop all threadpool->threads */
182         for (i = 0; i < threadpool->threads->len; ++i) {
183                 MonoInternalThread *thread = (MonoInternalThread*) g_ptr_array_index (threadpool->threads, i);
184                 if (thread != current)
185                         mono_thread_internal_abort (thread);
186         }
187
188         mono_coop_mutex_unlock (&threadpool->threads_lock);
189
190         /* give a chance to the other threads to exit */
191         mono_thread_info_yield ();
192
193         mono_coop_mutex_lock (&threadpool->threads_lock);
194
195         for (;;) {
196                 if (threadpool->threads->len == 0)
197                         break;
198
199                 if (threadpool->threads->len == 1 && g_ptr_array_index (threadpool->threads, 0) == current) {
200                         /* We are waiting on ourselves */
201                         break;
202                 }
203
204                 mono_coop_cond_wait (&threadpool->threads_exit_cond, &threadpool->threads_lock);
205         }
206
207         mono_coop_mutex_unlock (&threadpool->threads_lock);
208
209         mono_threadpool_worker_cleanup (threadpool->worker);
210
211         mono_refcount_dec (threadpool);
212 }
213
214 gboolean
215 mono_threadpool_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
216 {
217         static MonoClass *threadpool_class = NULL;
218         static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
219         MonoDomain *current_domain;
220         MonoBoolean f;
221         gpointer args [2];
222
223         mono_error_init (error);
224         g_assert (work_item);
225
226         if (!threadpool_class)
227                 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
228
229         if (!unsafe_queue_custom_work_item_method)
230                 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
231         g_assert (unsafe_queue_custom_work_item_method);
232
233         f = FALSE;
234
235         args [0] = (gpointer) work_item;
236         args [1] = (gpointer) &f;
237
238         current_domain = mono_domain_get ();
239         if (current_domain == domain) {
240                 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
241                 return_val_if_nok (error, FALSE);
242         } else {
243                 mono_thread_push_appdomain_ref (domain);
244                 if (mono_domain_set (domain, FALSE)) {
245                         mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
246                         if (!is_ok (error)) {
247                                 mono_thread_pop_appdomain_ref ();
248                                 return FALSE;
249                         }
250                         mono_domain_set (current_domain, TRUE);
251                 }
252                 mono_thread_pop_appdomain_ref ();
253         }
254         return TRUE;
255 }
256
257 /* LOCKING: domains_lock must be held */
258 static void
259 tpdomain_add (ThreadPoolDomain *tpdomain)
260 {
261         guint i, len;
262
263         g_assert (tpdomain);
264
265         len = threadpool->domains->len;
266         for (i = 0; i < len; ++i) {
267                 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
268                         break;
269         }
270
271         if (i == len)
272                 g_ptr_array_add (threadpool->domains, tpdomain);
273 }
274
275 /* LOCKING: domains_lock must be held. */
276 static gboolean
277 tpdomain_remove (ThreadPoolDomain *tpdomain)
278 {
279         g_assert (tpdomain);
280         return g_ptr_array_remove (threadpool->domains, tpdomain);
281 }
282
283 /* LOCKING: domains_lock must be held */
284 static ThreadPoolDomain *
285 tpdomain_get (MonoDomain *domain, gboolean create)
286 {
287         guint i;
288         ThreadPoolDomain *tpdomain;
289
290         g_assert (domain);
291
292         for (i = 0; i < threadpool->domains->len; ++i) {
293                 ThreadPoolDomain *tpdomain;
294
295                 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
296                 if (tpdomain->domain == domain)
297                         return tpdomain;
298         }
299
300         if (!create)
301                 return NULL;
302
303         tpdomain = g_new0 (ThreadPoolDomain, 1);
304         tpdomain->domain = domain;
305         mono_coop_cond_init (&tpdomain->cleanup_cond);
306
307         tpdomain_add (tpdomain);
308
309         return tpdomain;
310 }
311
312 static void
313 tpdomain_free (ThreadPoolDomain *tpdomain)
314 {
315         g_free (tpdomain);
316 }
317
318 /* LOCKING: domains_lock must be held */
319 static ThreadPoolDomain *
320 tpdomain_get_next (ThreadPoolDomain *current)
321 {
322         ThreadPoolDomain *tpdomain = NULL;
323         guint len;
324
325         len = threadpool->domains->len;
326         if (len > 0) {
327                 guint i, current_idx = -1;
328                 if (current) {
329                         for (i = 0; i < len; ++i) {
330                                 if (current == g_ptr_array_index (threadpool->domains, i)) {
331                                         current_idx = i;
332                                         break;
333                                 }
334                         }
335                         g_assert (current_idx != (guint)-1);
336                 }
337                 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
338                         ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i % len);
339                         if (tmp->outstanding_request > 0) {
340                                 tpdomain = tmp;
341                                 break;
342                         }
343                 }
344         }
345
346         return tpdomain;
347 }
348
349 static MonoObject*
350 try_invoke_perform_wait_callback (MonoObject** exc, MonoError *error)
351 {
352         HANDLE_FUNCTION_ENTER ();
353         mono_error_init (error);
354         MonoObject *res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, exc, error);
355         HANDLE_FUNCTION_RETURN_VAL (res);
356 }
357
358 static void
359 worker_callback (gpointer unused)
360 {
361         MonoError error;
362         ThreadPoolDomain *tpdomain, *previous_tpdomain;
363         ThreadPoolCounter counter;
364         MonoInternalThread *thread;
365
366         thread = mono_thread_internal_current ();
367
368         COUNTER_ATOMIC (threadpool, counter, {
369                 if (!(counter._.working < 32767 /* G_MAXINT16 */))
370                         g_error ("%s: counter._.working = %d, but should be < 32767", __func__, counter._.working);
371
372                 counter._.starting --;
373                 counter._.working ++;
374         });
375
376         if (mono_runtime_is_shutting_down ()) {
377                 COUNTER_ATOMIC (threadpool, counter, {
378                         counter._.working --;
379                 });
380
381                 mono_refcount_dec (threadpool);
382                 return;
383         }
384
385         mono_coop_mutex_lock (&threadpool->threads_lock);
386         g_ptr_array_add (threadpool->threads, thread);
387         mono_coop_mutex_unlock (&threadpool->threads_lock);
388
389         /*
390          * This is needed so there is always an lmf frame in the runtime invoke call below,
391          * so ThreadAbortExceptions are caught even if the thread is in native code.
392          */
393         mono_defaults.threadpool_perform_wait_callback_method->save_lmf = TRUE;
394
395         domains_lock ();
396
397         previous_tpdomain = NULL;
398
399         while (!mono_runtime_is_shutting_down ()) {
400                 gboolean retire = FALSE;
401
402                 if ((thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) != 0) {
403                         domains_unlock ();
404                         mono_thread_interruption_checkpoint ();
405                         domains_lock ();
406                 }
407
408                 tpdomain = tpdomain_get_next (previous_tpdomain);
409                 if (!tpdomain)
410                         break;
411
412                 tpdomain->outstanding_request --;
413                 g_assert (tpdomain->outstanding_request >= 0);
414
415                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d)",
416                         mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
417
418                 g_assert (tpdomain->threadpool_jobs >= 0);
419                 tpdomain->threadpool_jobs ++;
420
421                 domains_unlock ();
422
423                 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
424                 if (!mono_thread_test_state (thread , ThreadState_Background))
425                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
426
427                 mono_thread_push_appdomain_ref (tpdomain->domain);
428                 if (mono_domain_set (tpdomain->domain, FALSE)) {
429                         MonoObject *exc = NULL, *res;
430
431                         res = try_invoke_perform_wait_callback (&exc, &error);
432                         if (exc || !mono_error_ok(&error)) {
433                                 if (exc == NULL)
434                                         exc = (MonoObject *) mono_error_convert_to_exception (&error);
435                                 else
436                                         mono_error_cleanup (&error);
437                                 mono_thread_internal_unhandled_exception (exc);
438                         } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE) {
439                                 retire = TRUE;
440                         }
441
442                         mono_domain_set (mono_get_root_domain (), TRUE);
443                 }
444                 mono_thread_pop_appdomain_ref ();
445
446                 domains_lock ();
447
448                 tpdomain->threadpool_jobs --;
449                 g_assert (tpdomain->threadpool_jobs >= 0);
450
451                 if (tpdomain->outstanding_request + tpdomain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
452                         gboolean removed;
453
454                         removed = tpdomain_remove (tpdomain);
455                         g_assert (removed);
456
457                         mono_coop_cond_signal (&tpdomain->cleanup_cond);
458                         tpdomain = NULL;
459                 }
460
461                 if (retire)
462                         break;
463
464                 previous_tpdomain = tpdomain;
465         }
466
467         domains_unlock ();
468
469         mono_coop_mutex_lock (&threadpool->threads_lock);
470
471         g_ptr_array_remove_fast (threadpool->threads, thread);
472
473         mono_coop_cond_signal (&threadpool->threads_exit_cond);
474
475         mono_coop_mutex_unlock (&threadpool->threads_lock);
476
477         COUNTER_ATOMIC (threadpool, counter, {
478                 counter._.working --;
479         });
480
481         mono_refcount_dec (threadpool);
482 }
483
484 void
485 mono_threadpool_cleanup (void)
486 {
487 #ifndef DISABLE_SOCKETS
488         mono_threadpool_io_cleanup ();
489 #endif
490         mono_lazy_cleanup (&status, cleanup);
491 }
492
493 MonoAsyncResult *
494 mono_threadpool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
495 {
496         static MonoClass *async_call_klass = NULL;
497         MonoMethodMessage *message;
498         MonoAsyncResult *async_result;
499         MonoAsyncCall *async_call;
500         MonoDelegate *async_callback = NULL;
501         MonoObject *state = NULL;
502
503         if (!async_call_klass)
504                 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
505
506         mono_lazy_initialize (&status, initialize);
507
508         mono_error_init (error);
509
510         message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
511         return_val_if_nok (error, NULL);
512
513         async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
514         return_val_if_nok (error, NULL);
515
516         MONO_OBJECT_SETREF (async_call, msg, message);
517         MONO_OBJECT_SETREF (async_call, state, state);
518
519         if (async_callback) {
520                 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
521                 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
522         }
523
524         async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
525         return_val_if_nok (error, NULL);
526         MONO_OBJECT_SETREF (async_result, async_delegate, target);
527
528         mono_threadpool_enqueue_work_item (domain, (MonoObject*) async_result, error);
529         return_val_if_nok (error, NULL);
530
531         return async_result;
532 }
533
534 MonoObject *
535 mono_threadpool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
536 {
537         MonoAsyncCall *ac;
538
539         mono_error_init (error);
540         g_assert (exc);
541         g_assert (out_args);
542
543         *exc = NULL;
544         *out_args = NULL;
545
546         /* check if already finished */
547         mono_monitor_enter ((MonoObject*) ares);
548
549         if (ares->endinvoke_called) {
550                 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
551                 mono_monitor_exit ((MonoObject*) ares);
552                 return NULL;
553         }
554
555         ares->endinvoke_called = 1;
556
557         /* wait until we are really finished */
558         if (ares->completed) {
559                 mono_monitor_exit ((MonoObject *) ares);
560         } else {
561                 gpointer wait_event;
562                 if (ares->handle) {
563                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
564                 } else {
565                         wait_event = mono_w32event_create (TRUE, FALSE);
566                         g_assert(wait_event);
567                         MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
568                         if (!is_ok (error)) {
569                                 mono_w32event_close (wait_event);
570                                 return NULL;
571                         }
572                         MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
573                 }
574                 mono_monitor_exit ((MonoObject*) ares);
575                 MONO_ENTER_GC_SAFE;
576 #ifdef HOST_WIN32
577                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
578 #else
579                 mono_w32handle_wait_one (wait_event, MONO_INFINITE_WAIT, TRUE);
580 #endif
581                 MONO_EXIT_GC_SAFE;
582         }
583
584         ac = (MonoAsyncCall*) ares->object_data;
585         g_assert (ac);
586
587         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
588         *out_args = ac->out_args;
589         return ac->res;
590 }
591
592 gboolean
593 mono_threadpool_remove_domain_jobs (MonoDomain *domain, int timeout)
594 {
595         gint64 end;
596         ThreadPoolDomain *tpdomain;
597         gboolean ret;
598
599         g_assert (domain);
600         g_assert (timeout >= -1);
601
602         g_assert (mono_domain_is_unloading (domain));
603
604         if (timeout != -1)
605                 end = mono_msec_ticks () + timeout;
606
607 #ifndef DISABLE_SOCKETS
608         mono_threadpool_io_remove_domain_jobs (domain);
609         if (timeout != -1) {
610                 if (mono_msec_ticks () > end)
611                         return FALSE;
612         }
613 #endif
614
615         /*
616          * Wait for all threads which execute jobs in the domain to exit.
617          * The is_unloading () check in worker_request () ensures that
618          * no new jobs are added after we enter the lock below.
619          */
620
621         if (!mono_lazy_is_initialized (&status))
622                 return TRUE;
623
624         mono_refcount_inc (threadpool);
625
626         domains_lock ();
627
628         tpdomain = tpdomain_get (domain, FALSE);
629         if (!tpdomain) {
630                 domains_unlock ();
631                 mono_refcount_dec (threadpool);
632                 return TRUE;
633         }
634
635         ret = TRUE;
636
637         while (tpdomain->outstanding_request + tpdomain->threadpool_jobs > 0) {
638                 if (timeout == -1) {
639                         mono_coop_cond_wait (&tpdomain->cleanup_cond, &threadpool->domains_lock);
640                 } else {
641                         gint64 now;
642                         gint res;
643
644                         now = mono_msec_ticks();
645                         if (now > end) {
646                                 ret = FALSE;
647                                 break;
648                         }
649
650                         res = mono_coop_cond_timedwait (&tpdomain->cleanup_cond, &threadpool->domains_lock, end - now);
651                         if (res != 0) {
652                                 ret = FALSE;
653                                 break;
654                         }
655                 }
656         }
657
658         /* Remove from the list the worker threads look at */
659         tpdomain_remove (tpdomain);
660
661         domains_unlock ();
662
663         mono_coop_cond_destroy (&tpdomain->cleanup_cond);
664         tpdomain_free (tpdomain);
665
666         mono_refcount_dec (threadpool);
667
668         return ret;
669 }
670
671 void
672 mono_threadpool_suspend (void)
673 {
674         if (threadpool)
675                 mono_threadpool_worker_set_suspended (threadpool->worker, TRUE);
676 }
677
678 void
679 mono_threadpool_resume (void)
680 {
681         if (threadpool)
682                 mono_threadpool_worker_set_suspended (threadpool->worker, FALSE);
683 }
684
685 void
686 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
687 {
688         ThreadPoolCounter counter;
689
690         if (!worker_threads || !completion_port_threads)
691                 return;
692
693         mono_lazy_initialize (&status, initialize);
694
695         counter = COUNTER_READ (threadpool);
696
697         *worker_threads = MAX (0, mono_threadpool_worker_get_max (threadpool->worker) - counter._.working);
698         *completion_port_threads = threadpool->limit_io_max;
699 }
700
701 void
702 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
703 {
704         if (!worker_threads || !completion_port_threads)
705                 return;
706
707         mono_lazy_initialize (&status, initialize);
708
709         *worker_threads = mono_threadpool_worker_get_min (threadpool->worker);
710         *completion_port_threads = threadpool->limit_io_min;
711 }
712
713 void
714 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
715 {
716         if (!worker_threads || !completion_port_threads)
717                 return;
718
719         mono_lazy_initialize (&status, initialize);
720
721         *worker_threads = mono_threadpool_worker_get_max (threadpool->worker);
722         *completion_port_threads = threadpool->limit_io_max;
723 }
724
725 MonoBoolean
726 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
727 {
728         mono_lazy_initialize (&status, initialize);
729
730         if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
731                 return FALSE;
732
733         if (!mono_threadpool_worker_set_min (threadpool->worker, worker_threads))
734                 return FALSE;
735
736         threadpool->limit_io_min = completion_port_threads;
737
738         return TRUE;
739 }
740
741 MonoBoolean
742 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
743 {
744         gint cpu_count = mono_cpu_count ();
745
746         mono_lazy_initialize (&status, initialize);
747
748         if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
749                 return FALSE;
750
751         if (!mono_threadpool_worker_set_max (threadpool->worker, worker_threads))
752                 return FALSE;
753
754         threadpool->limit_io_max = completion_port_threads;
755
756         return TRUE;
757 }
758
759 void
760 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
761 {
762         if (enable_worker_tracking) {
763                 // TODO implement some kind of switch to have the possibily to use it
764                 *enable_worker_tracking = FALSE;
765         }
766
767         mono_lazy_initialize (&status, initialize);
768 }
769
770 MonoBoolean
771 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
772 {
773         if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
774                 return FALSE;
775
776         return mono_threadpool_worker_notify_completed (threadpool->worker);
777 }
778
779 void
780 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
781 {
782         mono_threadpool_worker_notify_completed (threadpool->worker);
783 }
784
785 void
786 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
787 {
788         // TODO
789         MonoError error;
790         mono_error_set_not_implemented (&error, "");
791         mono_error_set_pending_exception (&error);
792 }
793
794 MonoBoolean
795 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
796 {
797         MonoDomain *domain;
798         ThreadPoolDomain *tpdomain;
799         ThreadPoolCounter counter;
800
801         domain = mono_domain_get ();
802         if (mono_domain_is_unloading (domain))
803                 return FALSE;
804
805         if (!mono_refcount_tryinc (threadpool)) {
806                 /* threadpool has been destroyed, we are shutting down */
807                 return FALSE;
808         }
809
810         domains_lock ();
811
812         /* synchronize with mono_threadpool_remove_domain_jobs */
813         if (mono_domain_is_unloading (domain)) {
814                 domains_unlock ();
815                 mono_refcount_dec (threadpool);
816                 return FALSE;
817         }
818
819         tpdomain = tpdomain_get (domain, TRUE);
820         g_assert (tpdomain);
821
822         tpdomain->outstanding_request ++;
823         g_assert (tpdomain->outstanding_request >= 1);
824
825         domains_unlock ();
826
827         COUNTER_ATOMIC (threadpool, counter, {
828                 if (counter._.starting == 16) {
829                         mono_refcount_dec (threadpool);
830                         return TRUE;
831                 }
832
833                 counter._.starting ++;
834         });
835
836         mono_threadpool_worker_enqueue (threadpool->worker, worker_callback, NULL);
837
838         return TRUE;
839 }
840
841 MonoBoolean G_GNUC_UNUSED
842 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
843 {
844         /* This copy the behavior of the current Mono implementation */
845         MonoError error;
846         mono_error_set_not_implemented (&error, "");
847         mono_error_set_pending_exception (&error);
848         return FALSE;
849 }
850
851 MonoBoolean G_GNUC_UNUSED
852 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
853 {
854         /* This copy the behavior of the current Mono implementation */
855         return TRUE;
856 }
857
858 MonoBoolean G_GNUC_UNUSED
859 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)
860 {
861         return FALSE;
862 }