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