Merge pull request #2246 from BrzVlad/feature-concurrent-evacuation
[mono.git] / mono / metadata / threadpool-ms.c
1 /*
2  * threadpool-ms.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  */
9
10 //
11 // Copyright (c) Microsoft. All rights reserved.
12 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 //
14 // Files:
15 //  - src/vm/comthreadpool.cpp
16 //  - src/vm/win32threadpoolcpp
17 //  - src/vm/threadpoolrequest.cpp
18 //  - src/vm/hillclimbing.cpp
19 //
20 // Ported from C++ to C and adjusted to Mono runtime
21
22 #include <stdlib.h>
23 #define _USE_MATH_DEFINES // needed by MSVC to define math constants
24 #include <math.h>
25 #include <config.h>
26 #include <glib.h>
27
28 #include <mono/metadata/class-internals.h>
29 #include <mono/metadata/exception.h>
30 #include <mono/metadata/gc-internals.h>
31 #include <mono/metadata/object.h>
32 #include <mono/metadata/object-internals.h>
33 #include <mono/metadata/threadpool-ms.h>
34 #include <mono/metadata/threadpool-ms-io.h>
35 #include <mono/utils/atomic.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-complex.h>
38 #include <mono/utils/mono-lazy-init.h>
39 #include <mono/utils/mono-logger.h>
40 #include <mono/utils/mono-logger-internals.h>
41 #include <mono/utils/mono-proclib.h>
42 #include <mono/utils/mono-threads.h>
43 #include <mono/utils/mono-time.h>
44 #include <mono/utils/mono-rand.h>
45
46 #define CPU_USAGE_LOW 80
47 #define CPU_USAGE_HIGH 95
48
49 #define MONITOR_INTERVAL 100 // ms
50 #define MONITOR_MINIMAL_LIFETIME 60 * 1000 // ms
51
52 /* The exponent to apply to the gain. 1.0 means to use linear gain,
53  * higher values will enhance large moves and damp small ones.
54  * default: 2.0 */
55 #define HILL_CLIMBING_GAIN_EXPONENT 2.0
56
57 /* The 'cost' of a thread. 0 means drive for increased throughput regardless
58  * of thread count, higher values bias more against higher thread counts.
59  * default: 0.15 */
60 #define HILL_CLIMBING_BIAS 0.15
61
62 #define HILL_CLIMBING_WAVE_PERIOD 4
63 #define HILL_CLIMBING_MAX_WAVE_MAGNITUDE 20
64 #define HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER 1.0
65 #define HILL_CLIMBING_WAVE_HISTORY_SIZE 8
66 #define HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO 3.0
67 #define HILL_CLIMBING_MAX_CHANGE_PER_SECOND 4
68 #define HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE 20
69 #define HILL_CLIMBING_SAMPLE_INTERVAL_LOW 10
70 #define HILL_CLIMBING_SAMPLE_INTERVAL_HIGH 200
71 #define HILL_CLIMBING_ERROR_SMOOTHING_FACTOR 0.01
72 #define HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT 0.15
73
74 typedef union {
75         struct {
76                 gint16 max_working; /* determined by heuristic */
77                 gint16 active; /* executing worker_thread */
78                 gint16 working; /* actively executing worker_thread, not parked */
79                 gint16 parked; /* parked */
80         } _;
81         gint64 as_gint64;
82 } ThreadPoolCounter;
83
84 typedef struct {
85         MonoDomain *domain;
86         gint32 outstanding_request;
87 } ThreadPoolDomain;
88
89 typedef MonoInternalThread ThreadPoolWorkingThread;
90
91 typedef struct {
92         gint32 wave_period;
93         gint32 samples_to_measure;
94         gdouble target_throughput_ratio;
95         gdouble target_signal_to_noise_ratio;
96         gdouble max_change_per_second;
97         gdouble max_change_per_sample;
98         gint32 max_thread_wave_magnitude;
99         gint32 sample_interval_low;
100         gdouble thread_magnitude_multiplier;
101         gint32 sample_interval_high;
102         gdouble throughput_error_smoothing_factor;
103         gdouble gain_exponent;
104         gdouble max_sample_error;
105
106         gdouble current_control_setting;
107         gint64 total_samples;
108         gint16 last_thread_count;
109         gdouble elapsed_since_last_change;
110         gdouble completions_since_last_change;
111
112         gdouble average_throughput_noise;
113
114         gdouble *samples;
115         gdouble *thread_counts;
116
117         guint32 current_sample_interval;
118         gpointer random_interval_generator;
119
120         gint32 accumulated_completion_count;
121         gdouble accumulated_sample_duration;
122 } ThreadPoolHillClimbing;
123
124 typedef struct {
125         ThreadPoolCounter counters;
126
127         GPtrArray *domains; // ThreadPoolDomain* []
128         MonoCoopMutex domains_lock;
129
130         GPtrArray *working_threads; // ThreadPoolWorkingThread* []
131         gint32 parked_threads_count;
132         MonoCoopCond parked_threads_cond;
133         MonoCoopMutex active_threads_lock; /* protect access to working_threads and parked_threads */
134
135         gint32 heuristic_completions;
136         guint32 heuristic_sample_start;
137         guint32 heuristic_last_dequeue; // ms
138         guint32 heuristic_last_adjustment; // ms
139         guint32 heuristic_adjustment_interval; // ms
140         ThreadPoolHillClimbing heuristic_hill_climbing;
141         MonoCoopMutex heuristic_lock;
142
143         gint32 limit_worker_min;
144         gint32 limit_worker_max;
145         gint32 limit_io_min;
146         gint32 limit_io_max;
147
148         MonoCpuUsageState *cpu_usage_state;
149         gint32 cpu_usage;
150
151         /* suspended by the debugger */
152         gboolean suspended;
153 } ThreadPool;
154
155 typedef enum {
156         TRANSITION_WARMUP,
157         TRANSITION_INITIALIZING,
158         TRANSITION_RANDOM_MOVE,
159         TRANSITION_CLIMBING_MOVE,
160         TRANSITION_CHANGE_POINT,
161         TRANSITION_STABILIZING,
162         TRANSITION_STARVATION,
163         TRANSITION_THREAD_TIMED_OUT,
164         TRANSITION_UNDEFINED,
165 } ThreadPoolHeuristicStateTransition;
166
167 static mono_lazy_init_t status = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
168
169 enum {
170         MONITOR_STATUS_REQUESTED,
171         MONITOR_STATUS_WAITING_FOR_REQUEST,
172         MONITOR_STATUS_NOT_RUNNING,
173 };
174
175 static gint32 monitor_status = MONITOR_STATUS_NOT_RUNNING;
176
177 static ThreadPool* threadpool;
178
179 #define COUNTER_CHECK(counter) \
180         do { \
181                 g_assert (counter._.max_working > 0); \
182                 g_assert (counter._.working >= 0); \
183                 g_assert (counter._.active >= 0); \
184         } while (0)
185
186 #define COUNTER_READ() (InterlockedRead64 (&threadpool->counters.as_gint64))
187
188 #define COUNTER_ATOMIC(var,block) \
189         do { \
190                 ThreadPoolCounter __old; \
191                 do { \
192                         g_assert (threadpool); \
193                         __old.as_gint64 = COUNTER_READ (); \
194                         (var) = __old; \
195                         { block; } \
196                         COUNTER_CHECK (var); \
197                 } while (InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) != __old.as_gint64); \
198         } while (0)
199
200 #define COUNTER_TRY_ATOMIC(res,var,block) \
201         do { \
202                 ThreadPoolCounter __old; \
203                 do { \
204                         g_assert (threadpool); \
205                         __old.as_gint64 = COUNTER_READ (); \
206                         (var) = __old; \
207                         (res) = FALSE; \
208                         { block; } \
209                         COUNTER_CHECK (var); \
210                         (res) = InterlockedCompareExchange64 (&threadpool->counters.as_gint64, (var).as_gint64, __old.as_gint64) == __old.as_gint64; \
211                 } while (0); \
212         } while (0)
213
214 static gpointer
215 rand_create (void)
216 {
217         mono_rand_open ();
218         return mono_rand_init (NULL, 0);
219 }
220
221 static guint32
222 rand_next (gpointer *handle, guint32 min, guint32 max)
223 {
224         guint32 val;
225         if (!mono_rand_try_get_uint32 (handle, &val, min, max)) {
226                 // FIXME handle error
227                 g_assert_not_reached ();
228         }
229         return val;
230 }
231
232 static void
233 rand_free (gpointer handle)
234 {
235         mono_rand_close (handle);
236 }
237
238 static void
239 initialize (void)
240 {
241         ThreadPoolHillClimbing *hc;
242         const char *threads_per_cpu_env;
243         gint threads_per_cpu;
244         gint threads_count;
245
246         g_assert (!threadpool);
247         threadpool = g_new0 (ThreadPool, 1);
248         g_assert (threadpool);
249
250         threadpool->domains = g_ptr_array_new ();
251         mono_coop_mutex_init (&threadpool->domains_lock);
252
253         threadpool->parked_threads_count = 0;
254         mono_coop_cond_init (&threadpool->parked_threads_cond);
255         threadpool->working_threads = g_ptr_array_new ();
256         mono_coop_mutex_init (&threadpool->active_threads_lock);
257
258         threadpool->heuristic_adjustment_interval = 10;
259         mono_coop_mutex_init (&threadpool->heuristic_lock);
260
261         mono_rand_open ();
262
263         hc = &threadpool->heuristic_hill_climbing;
264
265         hc->wave_period = HILL_CLIMBING_WAVE_PERIOD;
266         hc->max_thread_wave_magnitude = HILL_CLIMBING_MAX_WAVE_MAGNITUDE;
267         hc->thread_magnitude_multiplier = (gdouble) HILL_CLIMBING_WAVE_MAGNITUDE_MULTIPLIER;
268         hc->samples_to_measure = hc->wave_period * HILL_CLIMBING_WAVE_HISTORY_SIZE;
269         hc->target_throughput_ratio = (gdouble) HILL_CLIMBING_BIAS;
270         hc->target_signal_to_noise_ratio = (gdouble) HILL_CLIMBING_TARGET_SIGNAL_TO_NOISE_RATIO;
271         hc->max_change_per_second = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SECOND;
272         hc->max_change_per_sample = (gdouble) HILL_CLIMBING_MAX_CHANGE_PER_SAMPLE;
273         hc->sample_interval_low = HILL_CLIMBING_SAMPLE_INTERVAL_LOW;
274         hc->sample_interval_high = HILL_CLIMBING_SAMPLE_INTERVAL_HIGH;
275         hc->throughput_error_smoothing_factor = (gdouble) HILL_CLIMBING_ERROR_SMOOTHING_FACTOR;
276         hc->gain_exponent = (gdouble) HILL_CLIMBING_GAIN_EXPONENT;
277         hc->max_sample_error = (gdouble) HILL_CLIMBING_MAX_SAMPLE_ERROR_PERCENT;
278         hc->current_control_setting = 0;
279         hc->total_samples = 0;
280         hc->last_thread_count = 0;
281         hc->average_throughput_noise = 0;
282         hc->elapsed_since_last_change = 0;
283         hc->accumulated_completion_count = 0;
284         hc->accumulated_sample_duration = 0;
285         hc->samples = g_new0 (gdouble, hc->samples_to_measure);
286         hc->thread_counts = g_new0 (gdouble, hc->samples_to_measure);
287         hc->random_interval_generator = rand_create ();
288         hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
289
290         if (!(threads_per_cpu_env = g_getenv ("MONO_THREADS_PER_CPU")))
291                 threads_per_cpu = 1;
292         else
293                 threads_per_cpu = CLAMP (atoi (threads_per_cpu_env), 1, 50);
294
295         threads_count = mono_cpu_count () * threads_per_cpu;
296
297         threadpool->limit_worker_min = threadpool->limit_io_min = threads_count;
298         threadpool->limit_worker_max = threadpool->limit_io_max = threads_count * 100;
299
300         threadpool->counters._.max_working = threadpool->limit_worker_min;
301
302         threadpool->cpu_usage_state = g_new0 (MonoCpuUsageState, 1);
303
304         threadpool->suspended = FALSE;
305 }
306
307 static void worker_kill (ThreadPoolWorkingThread *thread);
308
309 static void
310 cleanup (void)
311 {
312         guint i;
313
314         /* we make the assumption along the code that we are
315          * cleaning up only if the runtime is shutting down */
316         g_assert (mono_runtime_is_shutting_down ());
317
318         while (monitor_status != MONITOR_STATUS_NOT_RUNNING)
319                 mono_thread_info_sleep (1, NULL);
320
321         mono_coop_mutex_lock (&threadpool->active_threads_lock);
322
323         /* stop all threadpool->working_threads */
324         for (i = 0; i < threadpool->working_threads->len; ++i)
325                 worker_kill ((ThreadPoolWorkingThread*) g_ptr_array_index (threadpool->working_threads, i));
326
327         /* unpark all threadpool->parked_threads */
328         mono_coop_cond_broadcast (&threadpool->parked_threads_cond);
329
330         mono_coop_mutex_unlock (&threadpool->active_threads_lock);
331 }
332
333 void
334 mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item)
335 {
336         static MonoClass *threadpool_class = NULL;
337         static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
338         MonoDomain *current_domain;
339         MonoBoolean f;
340         gpointer args [2];
341
342         g_assert (work_item);
343
344         if (!threadpool_class)
345                 threadpool_class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "ThreadPool");
346         g_assert (threadpool_class);
347
348         if (!unsafe_queue_custom_work_item_method)
349                 unsafe_queue_custom_work_item_method = mono_class_get_method_from_name (threadpool_class, "UnsafeQueueCustomWorkItem", 2);
350         g_assert (unsafe_queue_custom_work_item_method);
351
352         f = FALSE;
353
354         args [0] = (gpointer) work_item;
355         args [1] = (gpointer) &f;
356
357         current_domain = mono_domain_get ();
358         if (current_domain == domain) {
359                 mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
360         } else {
361                 mono_thread_push_appdomain_ref (domain);
362                 if (mono_domain_set (domain, FALSE)) {
363                         mono_runtime_invoke (unsafe_queue_custom_work_item_method, NULL, args, NULL);
364                         mono_domain_set (current_domain, TRUE);
365                 }
366                 mono_thread_pop_appdomain_ref ();
367         }
368 }
369
370 /* LOCKING: threadpool->domains_lock must be held */
371 static void
372 domain_add (ThreadPoolDomain *tpdomain)
373 {
374         guint i, len;
375
376         g_assert (tpdomain);
377
378         len = threadpool->domains->len;
379         for (i = 0; i < len; ++i) {
380                 if (g_ptr_array_index (threadpool->domains, i) == tpdomain)
381                         break;
382         }
383
384         if (i == len)
385                 g_ptr_array_add (threadpool->domains, tpdomain);
386 }
387
388 /* LOCKING: threadpool->domains_lock must be held */
389 static gboolean
390 domain_remove (ThreadPoolDomain *tpdomain)
391 {
392         g_assert (tpdomain);
393         return g_ptr_array_remove (threadpool->domains, tpdomain);
394 }
395
396 /* LOCKING: threadpool->domains_lock must be held */
397 static ThreadPoolDomain *
398 domain_get (MonoDomain *domain, gboolean create)
399 {
400         ThreadPoolDomain *tpdomain = NULL;
401         guint i;
402
403         g_assert (domain);
404
405         for (i = 0; i < threadpool->domains->len; ++i) {
406                 tpdomain = g_ptr_array_index (threadpool->domains, i);
407                 if (tpdomain->domain == domain)
408                         return tpdomain;
409         }
410
411         if (create) {
412                 tpdomain = g_new0 (ThreadPoolDomain, 1);
413                 tpdomain->domain = domain;
414                 domain_add (tpdomain);
415         }
416
417         return tpdomain;
418 }
419
420 static void
421 domain_free (ThreadPoolDomain *tpdomain)
422 {
423         g_free (tpdomain);
424 }
425
426 /* LOCKING: threadpool->domains_lock must be held */
427 static gboolean
428 domain_any_has_request (void)
429 {
430         guint i;
431
432         for (i = 0; i < threadpool->domains->len; ++i) {
433                 ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i);
434                 if (tmp->outstanding_request > 0)
435                         return TRUE;
436         }
437
438         return FALSE;
439 }
440
441 /* LOCKING: threadpool->domains_lock must be held */
442 static ThreadPoolDomain *
443 domain_get_next (ThreadPoolDomain *current)
444 {
445         ThreadPoolDomain *tpdomain = NULL;
446         guint len;
447
448         len = threadpool->domains->len;
449         if (len > 0) {
450                 guint i, current_idx = -1;
451                 if (current) {
452                         for (i = 0; i < len; ++i) {
453                                 if (current == g_ptr_array_index (threadpool->domains, i)) {
454                                         current_idx = i;
455                                         break;
456                                 }
457                         }
458                         g_assert (current_idx >= 0);
459                 }
460                 for (i = current_idx + 1; i < len + current_idx + 1; ++i) {
461                         ThreadPoolDomain *tmp = g_ptr_array_index (threadpool->domains, i % len);
462                         if (tmp->outstanding_request > 0) {
463                                 tpdomain = tmp;
464                                 break;
465                         }
466                 }
467         }
468
469         return tpdomain;
470 }
471
472 static void
473 worker_wait_interrupt (gpointer data)
474 {
475         mono_coop_mutex_lock (&threadpool->active_threads_lock);
476         mono_coop_cond_signal (&threadpool->parked_threads_cond);
477         mono_coop_mutex_unlock (&threadpool->active_threads_lock);
478 }
479
480 /* return TRUE if timeout, FALSE otherwise (worker unpark or interrupt) */
481 static gboolean
482 worker_park (void)
483 {
484         gboolean timeout = FALSE;
485
486         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker parking", mono_native_thread_id_get ());
487
488         mono_gc_set_skip_thread (TRUE);
489
490         mono_coop_mutex_lock (&threadpool->active_threads_lock);
491
492         if (!mono_runtime_is_shutting_down ()) {
493                 static gpointer rand_handle = NULL;
494                 MonoInternalThread *thread_internal;
495                 gboolean interrupted = FALSE;
496
497                 if (!rand_handle)
498                         rand_handle = rand_create ();
499                 g_assert (rand_handle);
500
501                 thread_internal = mono_thread_internal_current ();
502                 g_assert (thread_internal);
503
504                 threadpool->parked_threads_count += 1;
505                 g_ptr_array_remove_fast (threadpool->working_threads, thread_internal);
506
507                 mono_thread_info_install_interrupt (worker_wait_interrupt, NULL, &interrupted);
508                 if (interrupted)
509                         goto done;
510
511                 if (mono_coop_cond_timedwait (&threadpool->parked_threads_cond, &threadpool->active_threads_lock, rand_next (rand_handle, 5 * 1000, 60 * 1000)) != 0)
512                         timeout = TRUE;
513
514                 mono_thread_info_uninstall_interrupt (&interrupted);
515
516 done:
517                 g_ptr_array_add (threadpool->working_threads, thread_internal);
518                 threadpool->parked_threads_count -= 1;
519         }
520
521         mono_coop_mutex_unlock (&threadpool->active_threads_lock);
522
523         mono_gc_set_skip_thread (FALSE);
524
525         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] current worker unparking, timeout? %s", mono_native_thread_id_get (), timeout ? "yes" : "no");
526
527         return timeout;
528 }
529
530 static gboolean
531 worker_try_unpark (void)
532 {
533         gboolean res = FALSE;
534
535         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker", mono_native_thread_id_get ());
536
537         mono_coop_mutex_lock (&threadpool->active_threads_lock);
538         if (threadpool->parked_threads_count > 0) {
539                 mono_coop_cond_signal (&threadpool->parked_threads_cond);
540                 res = TRUE;
541         }
542         mono_coop_mutex_unlock (&threadpool->active_threads_lock);
543
544         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try unpark worker, success? %s", mono_native_thread_id_get (), res ? "yes" : "no");
545
546         return res;
547 }
548
549 static void
550 worker_kill (ThreadPoolWorkingThread *thread)
551 {
552         if (thread == mono_thread_internal_current ())
553                 return;
554
555         mono_thread_internal_stop ((MonoInternalThread*) thread);
556 }
557
558 static void
559 worker_thread (gpointer data)
560 {
561         MonoInternalThread *thread;
562         ThreadPoolDomain *tpdomain, *previous_tpdomain;
563         ThreadPoolCounter counter;
564         gboolean retire = FALSE;
565
566         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker starting", mono_native_thread_id_get ());
567
568         g_assert (threadpool);
569
570         thread = mono_thread_internal_current ();
571         g_assert (thread);
572
573         mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), "Threadpool worker"), FALSE);
574
575         mono_coop_mutex_lock (&threadpool->active_threads_lock);
576         g_ptr_array_add (threadpool->working_threads, thread);
577         mono_coop_mutex_unlock (&threadpool->active_threads_lock);
578
579         previous_tpdomain = NULL;
580
581         mono_coop_mutex_lock (&threadpool->domains_lock);
582
583         while (!mono_runtime_is_shutting_down ()) {
584                 tpdomain = NULL;
585
586                 if ((thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0) {
587                         mono_coop_mutex_unlock (&threadpool->domains_lock);
588                         mono_thread_interruption_checkpoint ();
589                         mono_coop_mutex_lock (&threadpool->domains_lock);
590                 }
591
592                 if (retire || !(tpdomain = domain_get_next (previous_tpdomain))) {
593                         gboolean timeout;
594
595                         COUNTER_ATOMIC (counter, {
596                                 counter._.working --;
597                                 counter._.parked ++;
598                         });
599
600                         mono_coop_mutex_unlock (&threadpool->domains_lock);
601                         timeout = worker_park ();
602                         mono_coop_mutex_lock (&threadpool->domains_lock);
603
604                         COUNTER_ATOMIC (counter, {
605                                 counter._.working ++;
606                                 counter._.parked --;
607                         });
608
609                         if (timeout)
610                                 break;
611
612                         if (retire)
613                                 retire = FALSE;
614
615                         continue;
616                 }
617
618                 tpdomain->outstanding_request --;
619                 g_assert (tpdomain->outstanding_request >= 0);
620
621                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p",
622                         mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
623
624                 g_assert (tpdomain->domain);
625                 g_assert (tpdomain->domain->threadpool_jobs >= 0);
626                 tpdomain->domain->threadpool_jobs ++;
627
628                 mono_coop_mutex_unlock (&threadpool->domains_lock);
629
630                 mono_thread_push_appdomain_ref (tpdomain->domain);
631                 if (mono_domain_set (tpdomain->domain, FALSE)) {
632                         MonoObject *exc = NULL;
633                         MonoObject *res = mono_runtime_invoke (mono_defaults.threadpool_perform_wait_callback_method, NULL, NULL, &exc);
634                         if (exc)
635                                 mono_thread_internal_unhandled_exception (exc);
636                         else if (res && *(MonoBoolean*) mono_object_unbox (res) == FALSE)
637                                 retire = TRUE;
638
639                         mono_thread_clr_state (thread , ~ThreadState_Background);
640                         if (!mono_thread_test_state (thread , ThreadState_Background))
641                                 ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
642
643                         mono_domain_set (mono_get_root_domain (), TRUE);
644                 }
645                 mono_thread_pop_appdomain_ref ();
646
647                 mono_coop_mutex_lock (&threadpool->domains_lock);
648
649                 tpdomain->domain->threadpool_jobs --;
650                 g_assert (tpdomain->domain->threadpool_jobs >= 0);
651
652                 if (tpdomain->domain->threadpool_jobs == 0 && mono_domain_is_unloading (tpdomain->domain)) {
653                         gboolean removed = domain_remove (tpdomain);
654                         g_assert (removed);
655                         if (tpdomain->domain->cleanup_semaphore)
656                                 ReleaseSemaphore (tpdomain->domain->cleanup_semaphore, 1, NULL);
657                         domain_free (tpdomain);
658                         tpdomain = NULL;
659                 }
660
661                 previous_tpdomain = tpdomain;
662         }
663
664         mono_coop_mutex_unlock (&threadpool->domains_lock);
665
666         mono_coop_mutex_lock (&threadpool->active_threads_lock);
667         g_ptr_array_remove_fast (threadpool->working_threads, thread);
668         mono_coop_mutex_unlock (&threadpool->active_threads_lock);
669
670         COUNTER_ATOMIC (counter, {
671                 counter._.working--;
672                 counter._.active --;
673         });
674
675         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] worker finishing", mono_native_thread_id_get ());
676 }
677
678 static gboolean
679 worker_try_create (void)
680 {
681         ThreadPoolCounter counter;
682         MonoInternalThread *thread;
683
684         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker", mono_native_thread_id_get ());
685
686         COUNTER_ATOMIC (counter, {
687                 if (counter._.working >= counter._.max_working)
688                         return FALSE;
689                 counter._.working ++;
690                 counter._.active ++;
691         });
692
693         if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0)) != NULL) {
694                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p",
695                         mono_native_thread_id_get (), thread->tid);
696                 return TRUE;
697         }
698
699         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed", mono_native_thread_id_get ());
700
701         COUNTER_ATOMIC (counter, {
702                 counter._.working --;
703                 counter._.active --;
704         });
705
706         return FALSE;
707 }
708
709 static void monitor_ensure_running (void);
710
711 static gboolean
712 worker_request (MonoDomain *domain)
713 {
714         ThreadPoolDomain *tpdomain;
715
716         g_assert (domain);
717         g_assert (threadpool);
718
719         if (mono_runtime_is_shutting_down ())
720                 return FALSE;
721
722         mono_coop_mutex_lock (&threadpool->domains_lock);
723
724         /* synchronize check with worker_thread */
725         if (mono_domain_is_unloading (domain)) {
726                 mono_coop_mutex_unlock (&threadpool->domains_lock);
727                 return FALSE;
728         }
729
730         tpdomain = domain_get (domain, TRUE);
731         g_assert (tpdomain);
732         tpdomain->outstanding_request ++;
733
734         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, domain = %p, outstanding_request = %d",
735                 mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
736
737         mono_coop_mutex_unlock (&threadpool->domains_lock);
738
739         if (threadpool->suspended)
740                 return FALSE;
741
742         monitor_ensure_running ();
743
744         if (worker_try_unpark ()) {
745                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, unparked", mono_native_thread_id_get ());
746                 return TRUE;
747         }
748
749         if (worker_try_create ()) {
750                 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, created", mono_native_thread_id_get ());
751                 return TRUE;
752         }
753
754         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] request worker, failed", mono_native_thread_id_get ());
755         return FALSE;
756 }
757
758 static gboolean
759 monitor_should_keep_running (void)
760 {
761         static gint64 last_should_keep_running = -1;
762
763         g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
764
765         if (InterlockedExchange (&monitor_status, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST) {
766                 gboolean should_keep_running = TRUE, force_should_keep_running = FALSE;
767
768                 if (mono_runtime_is_shutting_down ()) {
769                         should_keep_running = FALSE;
770                 } else {
771                         mono_coop_mutex_lock (&threadpool->domains_lock);
772                         if (!domain_any_has_request ())
773                                 should_keep_running = FALSE;
774                         mono_coop_mutex_unlock (&threadpool->domains_lock);
775
776                         if (!should_keep_running) {
777                                 if (last_should_keep_running == -1 || mono_100ns_ticks () - last_should_keep_running < MONITOR_MINIMAL_LIFETIME * 1000 * 10) {
778                                         should_keep_running = force_should_keep_running = TRUE;
779                                 }
780                         }
781                 }
782
783                 if (should_keep_running) {
784                         if (last_should_keep_running == -1 || !force_should_keep_running)
785                                 last_should_keep_running = mono_100ns_ticks ();
786                 } else {
787                         last_should_keep_running = -1;
788                         if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_NOT_RUNNING, MONITOR_STATUS_WAITING_FOR_REQUEST) == MONITOR_STATUS_WAITING_FOR_REQUEST)
789                                 return FALSE;
790                 }
791         }
792
793         g_assert (monitor_status == MONITOR_STATUS_WAITING_FOR_REQUEST || monitor_status == MONITOR_STATUS_REQUESTED);
794
795         return TRUE;
796 }
797
798 static gboolean
799 monitor_sufficient_delay_since_last_dequeue (void)
800 {
801         guint32 threshold;
802
803         g_assert (threadpool);
804
805         if (threadpool->cpu_usage < CPU_USAGE_LOW) {
806                 threshold = MONITOR_INTERVAL;
807         } else {
808                 ThreadPoolCounter counter;
809                 counter.as_gint64 = COUNTER_READ();
810                 threshold = counter._.max_working * MONITOR_INTERVAL * 2;
811         }
812
813         return mono_msec_ticks () >= threadpool->heuristic_last_dequeue + threshold;
814 }
815
816 static void hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition);
817
818 static void
819 monitor_thread (void)
820 {
821         MonoInternalThread *current_thread = mono_thread_internal_current ();
822         guint i;
823
824         mono_cpu_usage (threadpool->cpu_usage_state);
825
826         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, started", mono_native_thread_id_get ());
827
828         do {
829                 MonoInternalThread *thread;
830                 gboolean all_waitsleepjoin = TRUE;
831                 gint32 interval_left = MONITOR_INTERVAL;
832                 gint32 awake = 0; /* number of spurious awakes we tolerate before doing a round of rebalancing */
833
834                 g_assert (monitor_status != MONITOR_STATUS_NOT_RUNNING);
835
836                 mono_gc_set_skip_thread (TRUE);
837
838                 do {
839                         guint32 ts;
840                         gboolean alerted = FALSE;
841
842                         if (mono_runtime_is_shutting_down ())
843                                 break;
844
845                         ts = mono_msec_ticks ();
846                         if (mono_thread_info_sleep (interval_left, &alerted) == 0)
847                                 break;
848                         interval_left -= mono_msec_ticks () - ts;
849
850                         mono_gc_set_skip_thread (FALSE);
851                         if ((current_thread->state & (ThreadState_StopRequested | ThreadState_SuspendRequested)) != 0)
852                                 mono_thread_interruption_checkpoint ();
853                         mono_gc_set_skip_thread (TRUE);
854                 } while (interval_left > 0 && ++awake < 10);
855
856                 mono_gc_set_skip_thread (FALSE);
857
858                 if (threadpool->suspended)
859                         continue;
860
861                 if (mono_runtime_is_shutting_down ())
862                         continue;
863
864                 mono_coop_mutex_lock (&threadpool->domains_lock);
865                 if (!domain_any_has_request ()) {
866                         mono_coop_mutex_unlock (&threadpool->domains_lock);
867                         continue;
868                 }
869                 mono_coop_mutex_unlock (&threadpool->domains_lock);
870
871
872                 mono_coop_mutex_lock (&threadpool->active_threads_lock);
873                 for (i = 0; i < threadpool->working_threads->len; ++i) {
874                         thread = g_ptr_array_index (threadpool->working_threads, i);
875                         if ((thread->state & ThreadState_WaitSleepJoin) == 0) {
876                                 all_waitsleepjoin = FALSE;
877                                 break;
878                         }
879                 }
880                 mono_coop_mutex_unlock (&threadpool->active_threads_lock);
881
882                 if (all_waitsleepjoin) {
883                         ThreadPoolCounter counter;
884                         COUNTER_ATOMIC (counter, { counter._.max_working ++; });
885                         hill_climbing_force_change (counter._.max_working, TRANSITION_STARVATION);
886                 }
887
888                 threadpool->cpu_usage = mono_cpu_usage (threadpool->cpu_usage_state);
889
890                 if (monitor_sufficient_delay_since_last_dequeue ()) {
891                         for (i = 0; i < 5; ++i) {
892                                 if (mono_runtime_is_shutting_down ())
893                                         break;
894
895                                 if (worker_try_unpark ()) {
896                                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, unparked", mono_native_thread_id_get ());
897                                         break;
898                                 }
899
900                                 if (worker_try_create ()) {
901                                         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, created", mono_native_thread_id_get ());
902                                         break;
903                                 }
904                         }
905                 }
906         } while (monitor_should_keep_running ());
907
908         mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] monitor thread, finished", mono_native_thread_id_get ());
909 }
910
911 static void
912 monitor_ensure_running (void)
913 {
914         for (;;) {
915                 switch (monitor_status) {
916                 case MONITOR_STATUS_REQUESTED:
917                         return;
918                 case MONITOR_STATUS_WAITING_FOR_REQUEST:
919                         InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_WAITING_FOR_REQUEST);
920                         break;
921                 case MONITOR_STATUS_NOT_RUNNING:
922                         if (mono_runtime_is_shutting_down ())
923                                 return;
924                         if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
925                                 if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK))
926                                         monitor_status = MONITOR_STATUS_NOT_RUNNING;
927                                 return;
928                         }
929                         break;
930                 default: g_assert_not_reached ();
931                 }
932         }
933 }
934
935 static void
936 hill_climbing_change_thread_count (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
937 {
938         ThreadPoolHillClimbing *hc;
939
940         g_assert (threadpool);
941
942         hc = &threadpool->heuristic_hill_climbing;
943
944         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_THREADPOOL, "[%p] hill climbing, change max number of threads %d", mono_native_thread_id_get (), new_thread_count);
945
946         hc->last_thread_count = new_thread_count;
947         hc->current_sample_interval = rand_next (&hc->random_interval_generator, hc->sample_interval_low, hc->sample_interval_high);
948         hc->elapsed_since_last_change = 0;
949         hc->completions_since_last_change = 0;
950 }
951
952 static void
953 hill_climbing_force_change (gint16 new_thread_count, ThreadPoolHeuristicStateTransition transition)
954 {
955         ThreadPoolHillClimbing *hc;
956
957         g_assert (threadpool);
958
959         hc = &threadpool->heuristic_hill_climbing;
960
961         if (new_thread_count != hc->last_thread_count) {
962                 hc->current_control_setting += new_thread_count - hc->last_thread_count;
963                 hill_climbing_change_thread_count (new_thread_count, transition);
964         }
965 }
966
967 static double_complex
968 hill_climbing_get_wave_component (gdouble *samples, guint sample_count, gdouble period)
969 {
970         ThreadPoolHillClimbing *hc;
971         gdouble w, cosine, sine, coeff, q0, q1, q2;
972         guint i;
973
974         g_assert (threadpool);
975         g_assert (sample_count >= period);
976         g_assert (period >= 2);
977
978         hc = &threadpool->heuristic_hill_climbing;
979
980         w = 2.0 * M_PI / period;
981         cosine = cos (w);
982         sine = sin (w);
983         coeff = 2.0 * cosine;
984         q0 = q1 = q2 = 0;
985
986         for (i = 0; i < sample_count; ++i) {
987                 q0 = coeff * q1 - q2 + samples [(hc->total_samples - sample_count + i) % hc->samples_to_measure];
988                 q2 = q1;
989                 q1 = q0;
990         }
991
992         return mono_double_complex_scalar_div (mono_double_complex_make (q1 - q2 * cosine, (q2 * sine)), ((gdouble)sample_count));
993 }
994
995 static gint16
996 hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, guint32 *adjustment_interval)
997 {
998         ThreadPoolHillClimbing *hc;
999         ThreadPoolHeuristicStateTransition transition;
1000         gdouble throughput;
1001         gdouble throughput_error_estimate;
1002         gdouble confidence;
1003         gdouble move;
1004         gdouble gain;
1005         gint sample_index;
1006         gint sample_count;
1007         gint new_thread_wave_magnitude;
1008         gint new_thread_count;
1009         double_complex thread_wave_component;
1010         double_complex throughput_wave_component;
1011         double_complex ratio;
1012
1013         g_assert (threadpool);
1014         g_assert (adjustment_interval);
1015
1016         hc = &threadpool->heuristic_hill_climbing;
1017
1018         /* If someone changed the thread count without telling us, update our records accordingly. */
1019         if (current_thread_count != hc->last_thread_count)
1020                 hill_climbing_force_change (current_thread_count, TRANSITION_INITIALIZING);
1021
1022         /* Update the cumulative stats for this thread count */
1023         hc->elapsed_since_last_change += sample_duration;
1024         hc->completions_since_last_change += completions;
1025
1026         /* Add in any data we've already collected about this sample */
1027         sample_duration += hc->accumulated_sample_duration;
1028         completions += hc->accumulated_completion_count;
1029
1030         /* We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
1031          * of each work item, we are goinng to be missing some data about what really happened during the
1032          * sample interval. The count produced by each thread includes an initial work item that may have
1033          * started well before the start of the interval, and each thread may have been running some new
1034          * work item for some time before the end of the interval, which did not yet get counted. So
1035          * our count is going to be off by +/- threadCount workitems.
1036          *
1037          * The exception is that the thread that reported to us last time definitely wasn't running any work
1038          * at that time, and the thread that's reporting now definitely isn't running a work item now. So
1039          * we really only need to consider threadCount-1 threads.
1040          *
1041          * Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
1042          *
1043          * We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
1044          * of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
1045          * then the next one likely will be too. The one after that will include the sum of the completions
1046          * we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
1047          * two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
1048          * range we're targeting, which will not be filtered by the frequency-domain translation. */
1049         if (hc->total_samples > 0 && ((current_thread_count - 1.0) / completions) >= hc->max_sample_error) {
1050                 /* Not accurate enough yet. Let's accumulate the data so
1051                  * far, and tell the ThreadPool to collect a little more. */
1052                 hc->accumulated_sample_duration = sample_duration;
1053                 hc->accumulated_completion_count = completions;
1054                 *adjustment_interval = 10;
1055                 return current_thread_count;
1056         }
1057
1058         /* We've got enouugh data for our sample; reset our accumulators for next time. */
1059         hc->accumulated_sample_duration = 0;
1060         hc->accumulated_completion_count = 0;
1061
1062         /* Add the current thread count and throughput sample to our history. */
1063         throughput = ((gdouble) completions) / sample_duration;
1064
1065         sample_index = hc->total_samples % hc->samples_to_measure;
1066         hc->samples [sample_index] = throughput;
1067         hc->thread_counts [sample_index] = current_thread_count;
1068         hc->total_samples ++;
1069
1070         /* Set up defaults for our metrics. */
1071         thread_wave_component = mono_double_complex_make(0, 0);
1072         throughput_wave_component = mono_double_complex_make(0, 0);
1073         throughput_error_estimate = 0;
1074         ratio = mono_double_complex_make(0, 0);
1075         confidence = 0;
1076
1077         transition = TRANSITION_WARMUP;
1078
1079         /* How many samples will we use? It must be at least the three wave periods we're looking for, and it must also
1080          * be a whole multiple of the primary wave's period; otherwise the frequency we're looking for will fall between
1081          * two frequency bands in the Fourier analysis, and we won't be able to measure it accurately. */
1082         sample_count = ((gint) MIN (hc->total_samples - 1, hc->samples_to_measure) / hc->wave_period) * hc->wave_period;
1083
1084         if (sample_count > hc->wave_period) {
1085                 guint i;
1086                 gdouble average_throughput;
1087                 gdouble average_thread_count;
1088                 gdouble sample_sum = 0;
1089                 gdouble thread_sum = 0;
1090
1091                 /* Average the throughput and thread count samples, so we can scale the wave magnitudes later. */
1092                 for (i = 0; i < sample_count; ++i) {
1093                         guint j = (hc->total_samples - sample_count + i) % hc->samples_to_measure;
1094                         sample_sum += hc->samples [j];
1095                         thread_sum += hc->thread_counts [j];
1096                 }
1097
1098                 average_throughput = sample_sum / sample_count;
1099                 average_thread_count = thread_sum / sample_count;
1100
1101                 if (average_throughput > 0 && average_thread_count > 0) {
1102                         gdouble noise_for_confidence, adjacent_period_1, adjacent_period_2;
1103
1104                         /* Calculate the periods of the adjacent frequency bands we'll be using to
1105                          * measure noise levels. We want the two adjacent Fourier frequency bands. */
1106                         adjacent_period_1 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) + 1);
1107                         adjacent_period_2 = sample_count / (((gdouble) sample_count) / ((gdouble) hc->wave_period) - 1);
1108
1109                         /* Get the the three different frequency components of the throughput (scaled by average
1110                          * throughput). Our "error" estimate (the amount of noise that might be present in the
1111                          * frequency band we're really interested in) is the average of the adjacent bands. */
1112                         throughput_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, hc->wave_period), average_throughput);
1113                         throughput_error_estimate = cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->samples, sample_count, adjacent_period_1), average_throughput));
1114
1115                         if (adjacent_period_2 <= sample_count) {
1116                                 throughput_error_estimate = MAX (throughput_error_estimate, cabs (mono_double_complex_scalar_div (hill_climbing_get_wave_component (
1117                                         hc->samples, sample_count, adjacent_period_2), average_throughput)));
1118                         }
1119
1120                         /* Do the same for the thread counts, so we have something to compare to. We don't
1121                          * measure thread count noise, because there is none; these are exact measurements. */
1122                         thread_wave_component = mono_double_complex_scalar_div (hill_climbing_get_wave_component (hc->thread_counts, sample_count, hc->wave_period), average_thread_count);
1123
1124                         /* Update our moving average of the throughput noise. We'll use this
1125                          * later as feedback to determine the new size of the thread wave. */
1126                         if (hc->average_throughput_noise == 0) {
1127                                 hc->average_throughput_noise = throughput_error_estimate;
1128                         } else {
1129                                 hc->average_throughput_noise = (hc->throughput_error_smoothing_factor * throughput_error_estimate)
1130                                         + ((1.0 + hc->throughput_error_smoothing_factor) * hc->average_throughput_noise);
1131                         }
1132
1133                         if (cabs (thread_wave_component) > 0) {
1134                                 /* Adjust the throughput wave so it's centered around the target wave,
1135                                  * and then calculate the adjusted throughput/thread ratio. */
1136                                 ratio = mono_double_complex_div (mono_double_complex_sub (throughput_wave_component, mono_double_complex_scalar_mul(thread_wave_component, hc->target_throughput_ratio)), thread_wave_component);
1137                                 transition = TRANSITION_CLIMBING_MOVE;
1138                         } else {
1139                                 ratio = mono_double_complex_make (0, 0);
1140                                 transition = TRANSITION_STABILIZING;
1141                         }
1142
1143                         noise_for_confidence = MAX (hc->average_throughput_noise, throughput_error_estimate);
1144                         if (noise_for_confidence > 0) {
1145                                 confidence = cabs (thread_wave_component) / noise_for_confidence / hc->target_signal_to_noise_ratio;
1146                         } else {
1147                                 /* there is no noise! */
1148                                 confidence = 1.0;
1149                         }
1150                 }
1151         }
1152
1153         /* We use just the real part of the complex ratio we just calculated. If the throughput signal
1154          * is exactly in phase with the thread signal, this will be the same as taking the magnitude of
1155          * the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
1156          * backward (because this indicates that our changes are having the opposite of the intended effect).
1157          * If they're 90 degrees out of phase, we won't move at all, because we can't tell wether we're
1158          * having a negative or positive effect on throughput. */
1159         move = creal (ratio);
1160         move = CLAMP (move, -1.0, 1.0);
1161
1162         /* Apply our confidence multiplier. */
1163         move *= CLAMP (confidence, -1.0, 1.0);
1164
1165         /* Now apply non-linear gain, such that values around zero are attenuated, while higher values
1166          * are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
1167         * if we're getting close, giving us rapid ramp-up without wild oscillations around the target. */
1168         gain = hc->max_change_per_second * sample_duration;
1169         move = pow (fabs (move), hc->gain_exponent) * (move >= 0.0 ? 1 : -1) * gain;
1170         move = MIN (move, hc->max_change_per_sample);
1171
1172         /* If the result was positive, and CPU is > 95%, refuse the move. */
1173         if (move > 0.0 && threadpool->cpu_usage > CPU_USAGE_HIGH)
1174                 move = 0.0;
1175
1176         /* Apply the move to our control setting. */
1177         hc->current_control_setting += move;
1178
1179         /* Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of the
1180          * throughput error.  This average starts at zero, so we'll start with a nice safe little wave at first. */
1181         new_thread_wave_magnitude = (gint)(0.5 + (hc->current_control_setting * hc->average_throughput_noise
1182                 * hc->target_signal_to_noise_ratio * hc->thread_magnitude_multiplier * 2.0));
1183         new_thread_wave_magnitude = CLAMP (new_thread_wave_magnitude, 1, hc->max_thread_wave_magnitude);
1184
1185         /* Make sure our control setting is within the ThreadPool's limits. */
1186         hc->current_control_setting = CLAMP (hc->current_control_setting, threadpool->limit_worker_min, threadpool->limit_worker_max - new_thread_wave_magnitude);
1187
1188         /* Calculate the new thread count (control setting + square wave). */
1189         new_thread_count = (gint)(hc->current_control_setting + new_thread_wave_magnitude * ((hc->total_samples / (hc->wave_period / 2)) % 2));
1190
1191         /* Make sure the new thread count doesn't exceed the ThreadPool's limits. */
1192         new_thread_count = CLAMP (new_thread_count, threadpool->limit_worker_min, threadpool->limit_worker_max);
1193
1194         if (new_thread_count != current_thread_count)
1195                 hill_climbing_change_thread_count (new_thread_count, transition);
1196
1197         if (creal (ratio) < 0.0 && new_thread_count == threadpool->limit_worker_min)
1198                 *adjustment_interval = (gint)(0.5 + hc->current_sample_interval * (10.0 * MAX (-1.0 * creal (ratio), 1.0)));
1199         else
1200                 *adjustment_interval = hc->current_sample_interval;
1201
1202         return new_thread_count;
1203 }
1204
1205 static void
1206 heuristic_notify_work_completed (void)
1207 {
1208         g_assert (threadpool);
1209
1210         InterlockedIncrement (&threadpool->heuristic_completions);
1211         threadpool->heuristic_last_dequeue = mono_msec_ticks ();
1212 }
1213
1214 static gboolean
1215 heuristic_should_adjust (void)
1216 {
1217         g_assert (threadpool);
1218
1219         if (threadpool->heuristic_last_dequeue > threadpool->heuristic_last_adjustment + threadpool->heuristic_adjustment_interval) {
1220                 ThreadPoolCounter counter;
1221                 counter.as_gint64 = COUNTER_READ();
1222                 if (counter._.working <= counter._.max_working)
1223                         return TRUE;
1224         }
1225
1226         return FALSE;
1227 }
1228
1229 static void
1230 heuristic_adjust (void)
1231 {
1232         g_assert (threadpool);
1233
1234         if (mono_coop_mutex_trylock (&threadpool->heuristic_lock) == 0) {
1235                 gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
1236                 guint32 sample_end = mono_msec_ticks ();
1237                 guint32 sample_duration = sample_end - threadpool->heuristic_sample_start;
1238
1239                 if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
1240                         ThreadPoolCounter counter;
1241                         gint16 new_thread_count;
1242
1243                         counter.as_gint64 = COUNTER_READ ();
1244                         new_thread_count = hill_climbing_update (counter._.max_working, sample_duration, completions, &threadpool->heuristic_adjustment_interval);
1245
1246                         COUNTER_ATOMIC (counter, { counter._.max_working = new_thread_count; });
1247
1248                         if (new_thread_count > counter._.max_working)
1249                                 worker_request (mono_domain_get ());
1250
1251                         threadpool->heuristic_sample_start = sample_end;
1252                         threadpool->heuristic_last_adjustment = mono_msec_ticks ();
1253                 }
1254
1255                 mono_coop_mutex_unlock (&threadpool->heuristic_lock);
1256         }
1257 }
1258
1259 void
1260 mono_threadpool_ms_cleanup (void)
1261 {
1262         #ifndef DISABLE_SOCKETS
1263                 mono_threadpool_ms_io_cleanup ();
1264         #endif
1265         mono_lazy_cleanup (&status, cleanup);
1266 }
1267
1268 MonoAsyncResult *
1269 mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params)
1270 {
1271         static MonoClass *async_call_klass = NULL;
1272         MonoMethodMessage *message;
1273         MonoAsyncResult *async_result;
1274         MonoAsyncCall *async_call;
1275         MonoDelegate *async_callback = NULL;
1276         MonoObject *state = NULL;
1277
1278         if (!async_call_klass)
1279                 async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
1280         g_assert (async_call_klass);
1281
1282         mono_lazy_initialize (&status, initialize);
1283
1284         message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL);
1285
1286         async_call = (MonoAsyncCall*) mono_object_new (domain, async_call_klass);
1287         MONO_OBJECT_SETREF (async_call, msg, message);
1288         MONO_OBJECT_SETREF (async_call, state, state);
1289
1290         if (async_callback) {
1291                 MONO_OBJECT_SETREF (async_call, cb_method, mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass));
1292                 MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
1293         }
1294
1295         async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call);
1296         MONO_OBJECT_SETREF (async_result, async_delegate, target);
1297
1298         mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result);
1299
1300         return async_result;
1301 }
1302
1303 MonoObject *
1304 mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
1305 {
1306         MonoAsyncCall *ac;
1307
1308         g_assert (exc);
1309         g_assert (out_args);
1310
1311         *exc = NULL;
1312         *out_args = NULL;
1313
1314         /* check if already finished */
1315         mono_monitor_enter ((MonoObject*) ares);
1316
1317         if (ares->endinvoke_called) {
1318                 *exc = (MonoObject*) mono_get_exception_invalid_operation (NULL);
1319                 mono_monitor_exit ((MonoObject*) ares);
1320                 return NULL;
1321         }
1322
1323         ares->endinvoke_called = 1;
1324
1325         /* wait until we are really finished */
1326         if (ares->completed) {
1327                 mono_monitor_exit ((MonoObject *) ares);
1328         } else {
1329                 gpointer wait_event;
1330                 if (ares->handle) {
1331                         wait_event = mono_wait_handle_get_handle ((MonoWaitHandle*) ares->handle);
1332                 } else {
1333                         wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1334                         g_assert(wait_event);
1335                         MONO_OBJECT_SETREF (ares, handle, (MonoObject*) mono_wait_handle_new (mono_object_domain (ares), wait_event));
1336                 }
1337                 mono_monitor_exit ((MonoObject*) ares);
1338                 MONO_PREPARE_BLOCKING;
1339                 WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
1340                 MONO_FINISH_BLOCKING;
1341         }
1342
1343         ac = (MonoAsyncCall*) ares->object_data;
1344         g_assert (ac);
1345
1346         *exc = ac->msg->exc; /* FIXME: GC add write barrier */
1347         *out_args = ac->out_args;
1348         return ac->res;
1349 }
1350
1351 gboolean
1352 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
1353 {
1354         gboolean res = TRUE;
1355         guint32 start;
1356         gpointer sem;
1357
1358         g_assert (domain);
1359         g_assert (timeout >= -1);
1360
1361         g_assert (mono_domain_is_unloading (domain));
1362
1363         if (timeout != -1)
1364                 start = mono_msec_ticks ();
1365
1366 #ifndef DISABLE_SOCKETS
1367         mono_threadpool_ms_io_remove_domain_jobs (domain);
1368         if (timeout != -1) {
1369                 timeout -= mono_msec_ticks () - start;
1370                 if (timeout < 0)
1371                         return FALSE;
1372         }
1373 #endif
1374
1375         /*
1376          * There might be some threads out that could be about to execute stuff from the given domain.
1377          * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
1378          */
1379         sem = domain->cleanup_semaphore = CreateSemaphore (NULL, 0, 1, NULL);
1380
1381         /*
1382          * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
1383          * and reading threadpool_jobs. Otherwise this thread could read a stale version of threadpool_jobs
1384          * and wait forever.
1385          */
1386         mono_memory_write_barrier ();
1387
1388         while (domain->threadpool_jobs) {
1389                 MONO_PREPARE_BLOCKING;
1390                 WaitForSingleObject (sem, timeout);
1391                 MONO_FINISH_BLOCKING;
1392                 if (timeout != -1) {
1393                         timeout -= mono_msec_ticks () - start;
1394                         if (timeout <= 0) {
1395                                 res = FALSE;
1396                                 break;
1397                         }
1398                 }
1399         }
1400
1401         domain->cleanup_semaphore = NULL;
1402         CloseHandle (sem);
1403
1404         return res;
1405 }
1406
1407 void
1408 mono_threadpool_ms_suspend (void)
1409 {
1410         if (threadpool)
1411                 threadpool->suspended = TRUE;
1412 }
1413
1414 void
1415 mono_threadpool_ms_resume (void)
1416 {
1417         if (threadpool)
1418                 threadpool->suspended = FALSE;
1419 }
1420
1421 void
1422 ves_icall_System_Threading_ThreadPool_GetAvailableThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1423 {
1424         if (!worker_threads || !completion_port_threads)
1425                 return;
1426
1427         mono_lazy_initialize (&status, initialize);
1428
1429         *worker_threads = threadpool->limit_worker_max;
1430         *completion_port_threads = threadpool->limit_io_max;
1431 }
1432
1433 void
1434 ves_icall_System_Threading_ThreadPool_GetMinThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1435 {
1436         if (!worker_threads || !completion_port_threads)
1437                 return;
1438
1439         mono_lazy_initialize (&status, initialize);
1440
1441         *worker_threads = threadpool->limit_worker_min;
1442         *completion_port_threads = threadpool->limit_io_min;
1443 }
1444
1445 void
1446 ves_icall_System_Threading_ThreadPool_GetMaxThreadsNative (gint32 *worker_threads, gint32 *completion_port_threads)
1447 {
1448         if (!worker_threads || !completion_port_threads)
1449                 return;
1450
1451         mono_lazy_initialize (&status, initialize);
1452
1453         *worker_threads = threadpool->limit_worker_max;
1454         *completion_port_threads = threadpool->limit_io_max;
1455 }
1456
1457 MonoBoolean
1458 ves_icall_System_Threading_ThreadPool_SetMinThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1459 {
1460         mono_lazy_initialize (&status, initialize);
1461
1462         if (worker_threads <= 0 || worker_threads > threadpool->limit_worker_max)
1463                 return FALSE;
1464         if (completion_port_threads <= 0 || completion_port_threads > threadpool->limit_io_max)
1465                 return FALSE;
1466
1467         threadpool->limit_worker_max = worker_threads;
1468         threadpool->limit_io_max = completion_port_threads;
1469
1470         return TRUE;
1471 }
1472
1473 MonoBoolean
1474 ves_icall_System_Threading_ThreadPool_SetMaxThreadsNative (gint32 worker_threads, gint32 completion_port_threads)
1475 {
1476         gint cpu_count = mono_cpu_count ();
1477
1478         mono_lazy_initialize (&status, initialize);
1479
1480         if (worker_threads < threadpool->limit_worker_min || worker_threads < cpu_count)
1481                 return FALSE;
1482         if (completion_port_threads < threadpool->limit_io_min || completion_port_threads < cpu_count)
1483                 return FALSE;
1484
1485         threadpool->limit_worker_max = worker_threads;
1486         threadpool->limit_io_max = completion_port_threads;
1487
1488         return TRUE;
1489 }
1490
1491 void
1492 ves_icall_System_Threading_ThreadPool_InitializeVMTp (MonoBoolean *enable_worker_tracking)
1493 {
1494         if (enable_worker_tracking) {
1495                 // TODO implement some kind of switch to have the possibily to use it
1496                 *enable_worker_tracking = FALSE;
1497         }
1498
1499         mono_lazy_initialize (&status, initialize);
1500 }
1501
1502 MonoBoolean
1503 ves_icall_System_Threading_ThreadPool_NotifyWorkItemComplete (void)
1504 {
1505         ThreadPoolCounter counter;
1506
1507         if (mono_domain_is_unloading (mono_domain_get ()) || mono_runtime_is_shutting_down ())
1508                 return FALSE;
1509
1510         heuristic_notify_work_completed ();
1511
1512         if (heuristic_should_adjust ())
1513                 heuristic_adjust ();
1514
1515         counter.as_gint64 = COUNTER_READ ();
1516         return counter._.working <= counter._.max_working;
1517 }
1518
1519 void
1520 ves_icall_System_Threading_ThreadPool_NotifyWorkItemProgressNative (void)
1521 {
1522         heuristic_notify_work_completed ();
1523
1524         if (heuristic_should_adjust ())
1525                 heuristic_adjust ();
1526 }
1527
1528 void
1529 ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
1530 {
1531         // TODO
1532         mono_raise_exception (mono_get_exception_not_implemented (NULL));
1533 }
1534
1535 MonoBoolean
1536 ves_icall_System_Threading_ThreadPool_RequestWorkerThread (void)
1537 {
1538         return worker_request (mono_domain_get ());
1539 }
1540
1541 MonoBoolean G_GNUC_UNUSED
1542 ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
1543 {
1544         /* This copy the behavior of the current Mono implementation */
1545         mono_raise_exception (mono_get_exception_not_implemented (NULL));
1546         return FALSE;
1547 }
1548
1549 MonoBoolean G_GNUC_UNUSED
1550 ves_icall_System_Threading_ThreadPool_BindIOCompletionCallbackNative (gpointer file_handle)
1551 {
1552         /* This copy the behavior of the current Mono implementation */
1553         return TRUE;
1554 }
1555
1556 MonoBoolean G_GNUC_UNUSED
1557 ves_icall_System_Threading_ThreadPool_IsThreadPoolHosted (void)
1558 {
1559         return FALSE;
1560 }