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