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