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