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