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