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