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