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