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