[threadpool] Assert that we do not overflow ThreadPoolCounter starting and working...
[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         g_free (threadpool);
135 }
136
137 static void
138 initialize (void)
139 {
140         g_assert (!threadpool);
141         threadpool = g_new0 (ThreadPool, 1);
142         g_assert (threadpool);
143
144         g_assert (sizeof (ThreadPoolCounter) == sizeof (gint32));
145
146         mono_refcount_init (threadpool, destroy);
147
148         threadpool->domains = g_ptr_array_new ();
149         mono_coop_mutex_init (&threadpool->domains_lock);
150
151         threadpool->threads = g_ptr_array_new ();
152         mono_coop_mutex_init (&threadpool->threads_lock);
153         mono_coop_cond_init (&threadpool->threads_exit_cond);
154
155         threadpool->limit_io_min = mono_cpu_count ();
156         threadpool->limit_io_max = CLAMP (threadpool->limit_io_min * 100, MIN (threadpool->limit_io_min, 200), MAX (threadpool->limit_io_min, 200));
157
158         mono_threadpool_worker_init (&threadpool->worker);
159 }
160
161 static void
162 cleanup (void)
163 {
164         guint i;
165         MonoInternalThread *current;
166
167         /* we make the assumption along the code that we are
168          * cleaning up only if the runtime is shutting down */
169         g_assert (mono_runtime_is_shutting_down ());
170
171         current = mono_thread_internal_current ();
172
173         mono_coop_mutex_lock (&threadpool->threads_lock);
174
175         /* stop all threadpool->threads */
176         for (i = 0; i < threadpool->threads->len; ++i) {
177                 MonoInternalThread *thread = (MonoInternalThread*) g_ptr_array_index (threadpool->threads, i);
178                 if (thread != current)
179                         mono_thread_internal_abort (thread);
180         }
181
182         mono_coop_mutex_unlock (&threadpool->threads_lock);
183
184         /* give a chance to the other threads to exit */
185         mono_thread_info_yield ();
186
187         mono_coop_mutex_lock (&threadpool->threads_lock);
188
189         for (;;) {
190                 ThreadPoolCounter counter;
191
192                 counter = COUNTER_READ (threadpool);
193                 if (counter._.working == 0)
194                         break;
195
196                 if (counter._.working == 1) {
197                         if (threadpool->threads->len == 1 && g_ptr_array_index (threadpool->threads, 0) == current) {
198                                 /* We are waiting on ourselves */
199                                 break;
200                         }
201                 }
202
203                 mono_coop_cond_wait (&threadpool->threads_exit_cond, &threadpool->threads_lock);
204         }
205
206         mono_coop_mutex_unlock (&threadpool->threads_lock);
207
208         mono_threadpool_worker_cleanup (threadpool->worker);
209
210         mono_refcount_dec (threadpool);
211 }
212
213 gboolean
214 mono_threadpool_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
215 {
216         static MonoClass *threadpool_class = NULL;
217         static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
218         MonoDomain *current_domain;
219         MonoBoolean f;
220         gpointer args [2];
221
222         mono_error_init (error);
223         g_assert (work_item);
224
225         if (!threadpool_class)
226                 threadpool_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
227
228         if (!unsafe_queue_custom_work_item_method)
229                 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
230         g_assert (unsafe_queue_custom_work_item_method);
231
232         f = FALSE;
233
234         args [0] = (gpointer) work_item;
235         args [1] = (gpointer) &f;
236
237         current_domain = mono_domain_get ();
238         if (current_domain == domain) {
239                 mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
240                 return_val_if_nok (error, FALSE);
241         } else {
242                 mono_thread_push_appdomain_ref (domain);
243                 if (mono_domain_set (domain, FALSE)) {
244                         mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
245                         if (!is_ok (error)) {
246                                 mono_thread_pop_appdomain_ref ();
247                                 return FALSE;
248                         }
249                         mono_domain_set (current_domain, TRUE);
250                 }
251                 mono_thread_pop_appdomain_ref ();
252         }
253         return TRUE;
254 }
255
256 /* LOCKING: domains_lock must be held */
257 static void
258 tpdomain_add (ThreadPoolDomain *tpdomain)
259 {
260         guint i, len;
261
262         g_assert (tpdomain);
263
264         len = threadpool->domains->len;
265         for (i = 0; i < len; ++i) {
266                 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
267                         break;
268         }
269
270         if (i == len)
271                 g_ptr_array_add (threadpool->domains, tpdomain);
272 }
273
274 /* LOCKING: domains_lock must be held. */
275 static gboolean
276 tpdomain_remove (ThreadPoolDomain *tpdomain)
277 {
278         g_assert (tpdomain);
279         return g_ptr_array_remove (threadpool->domains, tpdomain);
280 }
281
282 /* LOCKING: domains_lock must be held */
283 static ThreadPoolDomain *
284 tpdomain_get (MonoDomain *domain, gboolean create)
285 {
286         guint i;
287         ThreadPoolDomain *tpdomain;
288
289         g_assert (domain);
290
291         for (i = 0; i < threadpool->domains->len; ++i) {
292                 ThreadPoolDomain *tpdomain;
293
294                 tpdomain = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i);
295                 if (tpdomain->domain == domain)
296                         return tpdomain;
297         }
298
299         if (!create)
300                 return NULL;
301
302         tpdomain = g_new0 (ThreadPoolDomain, 1);
303         tpdomain->domain = domain;
304         mono_coop_cond_init (&tpdomain->cleanup_cond);
305
306         tpdomain_add (tpdomain);
307
308         return tpdomain;
309 }
310
311 static void
312 tpdomain_free (ThreadPoolDomain *tpdomain)
313 {
314         g_free (tpdomain);
315 }
316
317 /* LOCKING: domains_lock must be held */
318 static ThreadPoolDomain *
319 tpdomain_get_next (ThreadPoolDomain *current)
320 {
321         ThreadPoolDomain *tpdomain = NULL;
322         guint len;
323
324         len = threadpool->domains->len;
325         if (len > 0) {
326                 guint i, current_idx = -1;
327                 if (current) {
328                         for (i = 0; i < len; ++i) {
329                                 if (current == g_ptr_array_index (threadpool->domains, i)) {
330                                         current_idx = i;
331                                         break;
332                                 }
333                         }
334                         g_assert (current_idx != (guint)-1);
335                 }
336                 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
337                         ThreadPoolDomain *tmp = (ThreadPoolDomain *)g_ptr_array_index (threadpool->domains, i % len);
338                         if (tmp->outstanding_request > 0) {
339                                 tpdomain = tmp;
340                                 break;
341                         }
342                 }
343         }
344
345         return tpdomain;
346 }
347
348 static void
349 worker_callback (gpointer unused)
350 {
351         MonoError error;
352         ThreadPoolDomain *tpdomain, *previous_tpdomain;
353         ThreadPoolCounter counter;
354         MonoInternalThread *thread;
355
356         thread = mono_thread_internal_current ();
357
358         COUNTER_ATOMIC (threadpool, counter, {
359                 if (!(counter._.working < 32767 /* G_MAXINT16 */))
360                         g_error ("%s: counter._.working = %d, but should be < 32767", __func__, counter._.working);
361
362                 counter._.starting --;
363                 counter._.working ++;
364         });
365
366         if (mono_runtime_is_shutting_down ()) {
367                 COUNTER_ATOMIC (threadpool, counter, {
368                         counter._.working --;
369                 });
370
371                 mono_refcount_dec (threadpool);
372                 return;
373         }
374
375         mono_coop_mutex_lock (&threadpool->threads_lock);
376         g_ptr_array_add (threadpool->threads, thread);
377         mono_coop_mutex_unlock (&threadpool->threads_lock);
378
379         /*
380          * This is needed so there is always an lmf frame in the runtime invoke call below,
381          * so ThreadAbortExceptions are caught even if the thread is in native code.
382          */
383         mono_defaults.threadpool_perform_wait_callback_method->save_lmf = TRUE;
384
385         domains_lock ();
386
387         previous_tpdomain = NULL;
388
389         while (!mono_runtime_is_shutting_down ()) {
390                 gboolean retire = FALSE;
391
392                 if ((thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) != 0) {
393                         domains_unlock ();
394                         mono_thread_interruption_checkpoint ();
395                         domains_lock ();
396                 }
397
398                 tpdomain = tpdomain_get_next (previous_tpdomain);
399                 if (!tpdomain)
400                         break;
401
402                 tpdomain->outstanding_request --;
403                 g_assert (tpdomain->outstanding_request >= 0);
404
405                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d)",
406                         mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
407
408                 g_assert (tpdomain->threadpool_jobs >= 0);
409                 tpdomain->threadpool_jobs ++;
410
411                 domains_unlock ();
412
413                 mono_thread_clr_state (thread, (MonoThreadState)~ThreadState_Background);
414                 if (!mono_thread_test_state (thread , ThreadState_Background))
415                         ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
416
417                 mono_thread_push_appdomain_ref (tpdomain->domain);
418                 if (mono_domain_set (tpdomain->domain, FALSE)) {
419                         MonoObject *exc = NULL, *res;
420
421                         res = mono_runtime_try_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, &exc, &error);
422                         if (exc || !mono_error_ok(&error)) {
423                                 if (exc == NULL)
424                                         exc = (MonoObject *) mono_error_convert_to_exception (&error);
425                                 else
426                                         mono_error_cleanup (&error);
427                                 mono_thread_internal_unhandled_exception (exc);
428                         } else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE) {
429                                 retire = TRUE;
430                         }
431
432                         mono_domain_set (mono_get_root_domain (), TRUE);
433                 }
434                 mono_thread_pop_appdomain_ref ();
435
436                 domains_lock ();
437
438                 tpdomain->threadpool_jobs --;
439                 g_assert (tpdomain->threadpool_jobs >= 0);
440
441                 if (tpdomain->outstanding_request + tpdomain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
442                         gboolean removed;
443
444                         removed = tpdomain_remove (tpdomain);
445                         g_assert (removed);
446
447                         mono_coop_cond_signal (&tpdomain->cleanup_cond);
448                         tpdomain = NULL;
449                 }
450
451                 if (retire)
452                         break;
453
454                 previous_tpdomain = tpdomain;
455         }
456
457         domains_unlock ();
458
459         mono_coop_mutex_lock (&threadpool->threads_lock);
460
461         COUNTER_ATOMIC (threadpool, counter, {
462                 counter._.working --;
463         });
464
465         g_ptr_array_remove_fast (threadpool->threads, thread);
466
467         mono_coop_cond_signal (&threadpool->threads_exit_cond);
468
469         mono_coop_mutex_unlock (&threadpool->threads_lock);
470
471         mono_refcount_dec (threadpool);
472 }
473
474 void
475 mono_threadpool_cleanup (void)
476 {
477 #ifndef DISABLE_SOCKETS
478         mono_threadpool_io_cleanup ();
479 #endif
480         mono_lazy_cleanup (&status, cleanup);
481 }
482
483 MonoAsyncResult *
484 mono_threadpool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
485 {
486         static MonoClass *async_call_klass = NULL;
487         MonoMethodMessage *message;
488         MonoAsyncResult *async_result;
489         MonoAsyncCall *async_call;
490         MonoDelegate *async_callback = NULL;
491         MonoObject *state = NULL;
492
493         if (!async_call_klass)
494                 async_call_klass = mono_class_load_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
495
496         mono_lazy_initialize (&status, initialize);
497
498         mono_error_init (error);
499
500         message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL, error);
501         return_val_if_nok (error, NULL);
502
503         async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
504         return_val_if_nok (error, NULL);
505
506         MONO_OBJECT_SETREF (async_call, msg, message);
507         MONO_OBJECT_SETREF (async_call, state, state);
508
509         if (async_callback) {
510                 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
511                 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
512         }
513
514         async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call, error);
515         return_val_if_nok (error, NULL);
516         MONO_OBJECT_SETREF (async_result, async_delegate, target);
517
518         mono_threadpool_enqueue_work_item (domain, (MonoObject*) async_result, error);
519         return_val_if_nok (error, NULL);
520
521         return async_result;
522 }
523
524 MonoObject *
525 mono_threadpool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc, MonoError *error)
526 {
527         MonoAsyncCall *ac;
528
529         mono_error_init (error);
530         g_assert (exc);
531         g_assert (out_args);
532
533         *exc = NULL;
534         *out_args = NULL;
535
536         /* check if already finished */
537         mono_monitor_enter ((MonoObject*) ares);
538
539         if (ares->endinvoke_called) {
540                 mono_error_set_invalid_operation(error, "Delegate EndInvoke method called more than once");
541                 mono_monitor_exit ((MonoObject*) ares);
542                 return NULL;
543         }
544
545         ares->endinvoke_called = 1;
546
547         /* wait until we are really finished */
548         if (ares->completed) {
549                 mono_monitor_exit ((MonoObject *) ares);
550         } else {
551                 gpointer wait_event;
552                 if (ares->handle) {
553                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
554                 } else {
555                         wait_event = mono_w32event_create (TRUE, FALSE);
556                         g_assert(wait_event);
557                         MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, error);
558                         if (!is_ok (error)) {
559                                 CloseHandle (wait_event);
560                                 return NULL;
561                         }
562                         MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
563                 }
564                 mono_monitor_exit ((MonoObject*) ares);
565                 MONO_ENTER_GC_SAFE;
566 #ifdef HOST_WIN32
567                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
568 #else
569                 mono_w32handle_wait_one (wait_event, MONO_INFINITE_WAIT, TRUE);
570 #endif
571                 MONO_EXIT_GC_SAFE;
572         }
573
574         ac = (MonoAsyncCall*) ares->object_data;
575         g_assert (ac);
576
577         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
578         *out_args = ac->out_args;
579         return ac->res;
580 }
581
582 gboolean
583 mono_threadpool_remove_domain_jobs (MonoDomain *domain, int timeout)
584 {
585         gint64 end;
586         ThreadPoolDomain *tpdomain;
587         gboolean ret;
588
589         g_assert (domain);
590         g_assert (timeout >= -1);
591
592         g_assert (mono_domain_is_unloading (domain));
593
594         if (timeout != -1)
595                 end = mono_msec_ticks () + timeout;
596
597 #ifndef DISABLE_SOCKETS
598         mono_threadpool_io_remove_domain_jobs (domain);
599         if (timeout != -1) {
600                 if (mono_msec_ticks () > end)
601                         return FALSE;
602         }
603 #endif
604
605         /*
606          * Wait for all threads which execute jobs in the domain to exit.
607          * The is_unloading () check in worker_request () ensures that
608          * no new jobs are added after we enter the lock below.
609          */
610
611         if (!mono_lazy_is_initialized (&status))
612                 return TRUE;
613
614         mono_refcount_inc (threadpool);
615
616         domains_lock ();
617
618         tpdomain = tpdomain_get (domain, FALSE);
619         if (!tpdomain) {
620                 domains_unlock ();
621                 mono_refcount_dec (threadpool);
622                 return TRUE;
623         }
624
625         ret = TRUE;
626
627         while (tpdomain->outstanding_request + tpdomain->threadpool_jobs > 0) {
628                 if (timeout == -1) {
629                         mono_coop_cond_wait (&tpdomain->cleanup_cond, &threadpool->domains_lock);
630                 } else {
631                         gint64 now;
632                         gint res;
633
634                         now = mono_msec_ticks();
635                         if (now > end) {
636                                 ret = FALSE;
637                                 break;
638                         }
639
640                         res = mono_coop_cond_timedwait (&tpdomain->cleanup_cond, &threadpool->domains_lock, end - now);
641                         if (res != 0) {
642                                 ret = FALSE;
643                                 break;
644                         }
645                 }
646         }
647
648         /* Remove from the list the worker threads look at */
649         tpdomain_remove (tpdomain);
650
651         domains_unlock ();
652
653         mono_coop_cond_destroy (&tpdomain->cleanup_cond);
654         tpdomain_free (tpdomain);
655
656         mono_refcount_dec (threadpool);
657
658         return ret;
659 }
660
661 void
662 mono_threadpool_suspend (void)
663 {
664         if (threadpool)
665                 mono_threadpool_worker_set_suspended (threadpool->worker, TRUE);
666 }
667
668 void
669 mono_threadpool_resume (void)
670 {
671         if (threadpool)
672                 mono_threadpool_worker_set_suspended (threadpool->worker, FALSE);
673 }
674
675 void
676 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
677 {
678         ThreadPoolCounter counter;
679
680         if (!worker_threads || !completion_port_threads)
681                 return;
682
683         mono_lazy_initialize (&status, initialize);
684
685         counter = COUNTER_READ (threadpool);
686
687         *worker_threads = MAX (0, mono_threadpool_worker_get_max (threadpool->worker) - counter._.working);
688         *completion_port_threads = threadpool->limit_io_max;
689 }
690
691 void
692 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
693 {
694         if (!worker_threads || !completion_port_threads)
695                 return;
696
697         mono_lazy_initialize (&status, initialize);
698
699         *worker_threads = mono_threadpool_worker_get_min (threadpool->worker);
700         *completion_port_threads = threadpool->limit_io_min;
701 }
702
703 void
704 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
705 {
706         if (!worker_threads || !completion_port_threads)
707                 return;
708
709         mono_lazy_initialize (&status, initialize);
710
711         *worker_threads = mono_threadpool_worker_get_max (threadpool->worker);
712         *completion_port_threads = threadpool->limit_io_max;
713 }
714
715 MonoBoolean
716 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
717 {
718         mono_lazy_initialize (&status, initialize);
719
720         if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
721                 return FALSE;
722
723         if (!mono_threadpool_worker_set_min (threadpool->worker, worker_threads))
724                 return FALSE;
725
726         threadpool->limit_io_min = completion_port_threads;
727
728         return TRUE;
729 }
730
731 MonoBoolean
732 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
733 {
734         gint cpu_count = mono_cpu_count ();
735
736         mono_lazy_initialize (&status, initialize);
737
738         if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
739                 return FALSE;
740
741         if (!mono_threadpool_worker_set_max (threadpool->worker, worker_threads))
742                 return FALSE;
743
744         threadpool->limit_io_max = completion_port_threads;
745
746         return TRUE;
747 }
748
749 void
750 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
751 {
752         if (enable_worker_tracking) {
753                 // TODO implement some kind of switch to have the possibily to use it
754                 *enable_worker_tracking = FALSE;
755         }
756
757         mono_lazy_initialize (&status, initialize);
758 }
759
760 MonoBoolean
761 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
762 {
763         if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
764                 return FALSE;
765
766         return mono_threadpool_worker_notify_completed (threadpool->worker);
767 }
768
769 void
770 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
771 {
772         mono_threadpool_worker_notify_completed (threadpool->worker);
773 }
774
775 void
776 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
777 {
778         // TODO
779         MonoError error;
780         mono_error_set_not_implemented (&error, "");
781         mono_error_set_pending_exception (&error);
782 }
783
784 MonoBoolean
785 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
786 {
787         MonoDomain *domain;
788         ThreadPoolDomain *tpdomain;
789         ThreadPoolCounter counter;
790
791         domain = mono_domain_get ();
792         if (mono_domain_is_unloading (domain))
793                 return FALSE;
794
795         domains_lock ();
796
797         /* synchronize with mono_threadpool_remove_domain_jobs */
798         if (mono_domain_is_unloading (domain)) {
799                 domains_unlock ();
800                 return FALSE;
801         }
802
803         tpdomain = tpdomain_get (domain, TRUE);
804         g_assert (tpdomain);
805
806         tpdomain->outstanding_request ++;
807         g_assert (tpdomain->outstanding_request >= 1);
808
809         mono_refcount_inc (threadpool);
810
811         COUNTER_ATOMIC (threadpool, counter, {
812                 if (!(counter._.starting < 32767 /* G_MAXINT16 */))
813                         g_error ("%s: counter._.starting = %d, but should be < 32767", __func__, counter._.starting);
814
815                 counter._.starting ++;
816         });
817
818         mono_threadpool_worker_enqueue (threadpool->worker, worker_callback, NULL);
819
820         domains_unlock ();
821
822         return TRUE;
823 }
824
825 MonoBoolean G_GNUC_UNUSED
826 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
827 {
828         /* This copy the behavior of the current Mono implementation */
829         MonoError error;
830         mono_error_set_not_implemented (&error, "");
831         mono_error_set_pending_exception (&error);
832         return FALSE;
833 }
834
835 MonoBoolean G_GNUC_UNUSED
836 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
837 {
838         /* This copy the behavior of the current Mono implementation */
839         return TRUE;
840 }
841
842 MonoBoolean G_GNUC_UNUSED
843 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)
844 {
845         return FALSE;
846 }