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