Merge pull request #2979 from akoeplinger/tests-simplify
[mono.git] / mono / utils / mono-threads-coop.c
1  /*
2  * mono-threads.c: Coop threading
3  *
4  * Author:
5  *      Rodrigo Kumpera (kumpera@gmail.com)
6  *
7  * Copyright 2015 Xamarin, Inc (http://www.xamarin.com)
8  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
9  */
10
11 #include <config.h>
12
13 /* enable pthread extensions */
14 #ifdef TARGET_MACH
15 #define _DARWIN_C_SOURCE
16 #endif
17
18 #include <mono/utils/mono-compiler.h>
19 #include <mono/utils/mono-threads.h>
20 #include <mono/utils/mono-tls.h>
21 #include <mono/utils/hazard-pointer.h>
22 #include <mono/utils/mono-memory-model.h>
23 #include <mono/utils/mono-mmap.h>
24 #include <mono/utils/atomic.h>
25 #include <mono/utils/mono-time.h>
26 #include <mono/utils/mono-counters.h>
27 #include <mono/utils/mono-threads-coop.h>
28 #include <mono/utils/mono-threads-api.h>
29 #include <mono/utils/checked-build.h>
30
31 #ifdef TARGET_OSX
32 #include <mono/utils/mach-support.h>
33 #endif
34
35 #ifdef _MSC_VER
36 // TODO: Find MSVC replacement for __builtin_unwind_init
37 #define SAVE_REGS_ON_STACK g_assert_not_reached ();
38 #else 
39 #define SAVE_REGS_ON_STACK __builtin_unwind_init ();
40 #endif
41
42 volatile size_t mono_polling_required;
43
44 // FIXME: This would be more efficient if instead of instantiating the stack it just pushed a simple depth counter up and down,
45 // perhaps with a per-thread cookie in the high bits.
46 #ifdef ENABLE_CHECKED_BUILD_GC
47
48 // Maintains a single per-thread stack of ints, used to ensure nesting is not violated
49 static MonoNativeTlsKey coop_reset_count_stack_key;
50
51 static void
52 coop_tls_push (gpointer cookie)
53 {
54         GArray *stack;
55
56         stack = mono_native_tls_get_value (coop_reset_count_stack_key);
57         if (!stack) {
58                 stack = g_array_new (FALSE, FALSE, sizeof(gpointer));
59                 mono_native_tls_set_value (coop_reset_count_stack_key, stack);
60         }
61
62         g_array_append_val (stack, cookie);
63 }
64
65 static void
66 coop_tls_pop (gpointer received_cookie)
67 {
68         GArray *stack;
69         gpointer expected_cookie;
70
71         stack = mono_native_tls_get_value (coop_reset_count_stack_key);
72         if (!stack || 0 == stack->len)
73                 mono_fatal_with_history ("Received cookie %p but found no stack at all, %x\n", received_cookie);
74
75         expected_cookie = g_array_index (stack, gpointer, stack->len - 1);
76         stack->len --;
77
78         if (0 == stack->len) {
79                 g_array_free (stack,TRUE);
80                 mono_native_tls_set_value (coop_reset_count_stack_key, NULL);
81         }
82
83         if (expected_cookie != received_cookie)
84                 mono_fatal_with_history ("Received cookie %p but expected %p\n", received_cookie, expected_cookie);
85 }
86
87 #endif
88
89 static int coop_reset_blocking_count;
90 static int coop_try_blocking_count;
91 static int coop_do_blocking_count;
92 static int coop_do_polling_count;
93 static int coop_save_count;
94
95 void
96 mono_threads_state_poll (void)
97 {
98         MonoThreadInfo *info;
99
100         g_assert (mono_threads_is_coop_enabled ());
101
102         ++coop_do_polling_count;
103
104         info = mono_thread_info_current_unchecked ();
105         if (!info)
106                 return;
107         THREADS_SUSPEND_DEBUG ("FINISH SELF SUSPEND OF %p\n", mono_thread_info_get_tid (info));
108
109         /* Fast check for pending suspend requests */
110         if (!(info->thread_state & (STATE_ASYNC_SUSPEND_REQUESTED | STATE_SELF_SUSPEND_REQUESTED)))
111                 return;
112
113         ++coop_save_count;
114         mono_threads_get_runtime_callbacks ()->thread_state_init (&info->thread_saved_state [SELF_SUSPEND_STATE_INDEX]);
115
116         /* commit the saved state and notify others if needed */
117         switch (mono_threads_transition_state_poll (info)) {
118         case SelfSuspendResumed:
119                 return;
120         case SelfSuspendWait:
121                 mono_thread_info_wait_for_resume (info);
122                 break;
123         case SelfSuspendNotifyAndWait:
124                 mono_threads_notify_initiator_of_suspend (info);
125                 mono_thread_info_wait_for_resume (info);
126                 break;
127         }
128 }
129
130 static void *
131 return_stack_ptr ()
132 {
133         gpointer i;
134         return &i;
135 }
136
137 static void
138 copy_stack_data (MonoThreadInfo *info, gpointer *stackdata_begin)
139 {
140         MonoThreadUnwindState *state;
141         int stackdata_size;
142         void* stackdata_end = return_stack_ptr ();
143
144         SAVE_REGS_ON_STACK;
145
146         state = &info->thread_saved_state [SELF_SUSPEND_STATE_INDEX];
147
148         stackdata_size = (char*)stackdata_begin - (char*)stackdata_end;
149
150         if (((gsize) stackdata_begin & (SIZEOF_VOID_P - 1)) != 0)
151                 g_error ("stackdata_begin (%p) must be %d-byte aligned", stackdata_begin, SIZEOF_VOID_P);
152         if (((gsize) stackdata_end & (SIZEOF_VOID_P - 1)) != 0)
153                 g_error ("stackdata_end (%p) must be %d-byte aligned", stackdata_end, SIZEOF_VOID_P);
154
155         if (stackdata_size <= 0)
156                 g_error ("stackdata_size = %d, but must be > 0, stackdata_begin = %p, stackdata_end = %p", stackdata_size, stackdata_begin, stackdata_end);
157
158         g_byte_array_set_size (info->stackdata, stackdata_size);
159         state->gc_stackdata = info->stackdata->data;
160         memcpy (state->gc_stackdata, stackdata_end, stackdata_size);
161
162         state->gc_stackdata_size = stackdata_size;
163 }
164
165 gpointer
166 mono_threads_enter_gc_safe_region (gpointer *stackdata)
167 {
168         gpointer cookie;
169
170         if (!mono_threads_is_coop_enabled ())
171                 return NULL;
172
173         cookie = mono_threads_enter_gc_safe_region_unbalanced (stackdata);
174
175 #ifdef ENABLE_CHECKED_BUILD_GC
176         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
177                 coop_tls_push (cookie);
178 #endif
179
180         return cookie;
181 }
182
183 gpointer
184 mono_threads_enter_gc_safe_region_unbalanced (gpointer *stackdata)
185 {
186         MonoThreadInfo *info;
187
188         if (!mono_threads_is_coop_enabled ())
189                 return NULL;
190
191         ++coop_do_blocking_count;
192
193         info = mono_thread_info_current_unchecked ();
194         /* If the thread is not attached, it doesn't make sense prepare for suspend. */
195         if (!info || !mono_thread_info_is_live (info)) {
196                 THREADS_SUSPEND_DEBUG ("PREPARE-BLOCKING failed %p\n", info ? mono_thread_info_get_tid (info) : NULL);
197                 return NULL;
198         }
199
200         copy_stack_data (info, stackdata);
201
202 retry:
203         ++coop_save_count;
204         mono_threads_get_runtime_callbacks ()->thread_state_init (&info->thread_saved_state [SELF_SUSPEND_STATE_INDEX]);
205
206         switch (mono_threads_transition_do_blocking (info)) {
207         case DoBlockingContinue:
208                 break;
209         case DoBlockingPollAndRetry:
210                 mono_threads_state_poll ();
211                 goto retry;
212         }
213
214         return info;
215 }
216
217 void
218 mono_threads_exit_gc_safe_region (gpointer cookie, gpointer *stackdata)
219 {
220         if (!mono_threads_is_coop_enabled ())
221                 return;
222
223 #ifdef ENABLE_CHECKED_BUILD_GC
224         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
225                 coop_tls_pop (cookie);
226 #endif
227
228         mono_threads_exit_gc_safe_region_unbalanced (cookie, stackdata);
229 }
230
231 void
232 mono_threads_exit_gc_safe_region_unbalanced (gpointer cookie, gpointer *stackdata)
233 {
234         static gboolean warned_about_bad_transition;
235         MonoThreadInfo *info;
236
237         if (!mono_threads_is_coop_enabled ())
238                 return;
239
240         info = (MonoThreadInfo *)cookie;
241         if (!info)
242                 return;
243
244         g_assert (info == mono_thread_info_current_unchecked ());
245
246         switch (mono_threads_transition_done_blocking (info)) {
247         case DoneBlockingAborted:
248                 if (!warned_about_bad_transition) {
249                         warned_about_bad_transition = TRUE;
250                         g_warning ("[%p] Blocking call ended in running state for, this might lead to unbound GC pauses.", mono_thread_info_get_tid (info));
251                 }
252                 mono_threads_state_poll ();
253                 break;
254         case DoneBlockingOk:
255                 info->thread_saved_state [SELF_SUSPEND_STATE_INDEX].valid = FALSE;
256                 break;
257         case DoneBlockingWait:
258                 THREADS_SUSPEND_DEBUG ("state polling done, notifying of resume\n");
259                 mono_thread_info_wait_for_resume (info);
260                 break;
261         default:
262                 g_error ("Unknown thread state");
263         }
264 }
265
266 void
267 mono_threads_assert_gc_safe_region (void)
268 {
269         MONO_REQ_GC_SAFE_MODE;
270 }
271
272 gpointer
273 mono_threads_enter_gc_unsafe_region (gpointer *stackdata)
274 {
275         gpointer cookie;
276
277         if (!mono_threads_is_coop_enabled ())
278                 return NULL;
279
280         cookie = mono_threads_enter_gc_unsafe_region_unbalanced (stackdata);
281
282 #ifdef ENABLE_CHECKED_BUILD_GC
283         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
284                 coop_tls_push (cookie);
285 #endif
286
287         return cookie;
288 }
289
290 gpointer
291 mono_threads_enter_gc_unsafe_region_unbalanced (gpointer *stackdata)
292 {
293         MonoThreadInfo *info;
294
295         if (!mono_threads_is_coop_enabled ())
296                 return NULL;
297
298         ++coop_reset_blocking_count;
299
300         info = mono_thread_info_current_unchecked ();
301
302         /* If the thread is not attached, it doesn't make sense prepare for suspend. */
303         if (!info || !mono_thread_info_is_live (info))
304                 return NULL;
305
306         copy_stack_data (info, stackdata);
307
308         switch (mono_threads_transition_abort_blocking (info)) {
309         case AbortBlockingIgnore:
310                 info->thread_saved_state [SELF_SUSPEND_STATE_INDEX].valid = FALSE;
311                 return NULL;
312         case AbortBlockingIgnoreAndPoll:
313                 mono_threads_state_poll ();
314                 return NULL;
315         case AbortBlockingOk:
316                 info->thread_saved_state [SELF_SUSPEND_STATE_INDEX].valid = FALSE;
317                 break;
318         case AbortBlockingWait:
319                 mono_thread_info_wait_for_resume (info);
320                 break;
321         default:
322                 g_error ("Unknown thread state");
323         }
324
325         return info;
326 }
327
328 gpointer
329 mono_threads_enter_gc_unsafe_region_cookie (MonoThreadInfo *info)
330 {
331         g_assert (mono_threads_is_coop_enabled ());
332
333 #ifdef ENABLE_CHECKED_BUILD_GC
334         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
335                 coop_tls_push (info);
336 #endif
337
338         return info;
339 }
340
341 void
342 mono_threads_exit_gc_unsafe_region (gpointer cookie, gpointer *stackdata)
343 {
344         if (!mono_threads_is_coop_enabled ())
345                 return;
346
347 #ifdef ENABLE_CHECKED_BUILD_GC
348         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
349                 coop_tls_pop (cookie);
350 #endif
351
352         mono_threads_exit_gc_unsafe_region_unbalanced (cookie, stackdata);
353 }
354
355 void
356 mono_threads_exit_gc_unsafe_region_unbalanced (gpointer cookie, gpointer *stackdata)
357 {
358         if (!mono_threads_is_coop_enabled ())
359                 return;
360
361         if (!cookie)
362                 return;
363
364 #ifdef ENABLE_CHECKED_BUILD_GC
365         if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC))
366 #endif
367         {
368                 g_assert (((MonoThreadInfo *)cookie) == mono_thread_info_current_unchecked ());
369         }
370
371         mono_threads_enter_gc_safe_region_unbalanced (stackdata);
372 }
373
374 void
375 mono_threads_assert_gc_unsafe_region (void)
376 {
377         MONO_REQ_GC_UNSAFE_MODE;
378 }
379
380 void
381 mono_threads_init_coop (void)
382 {
383         if (!mono_threads_is_coop_enabled ())
384                 return;
385
386         mono_counters_register ("Coop Reset Blocking", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_reset_blocking_count);
387         mono_counters_register ("Coop Try Blocking", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_try_blocking_count);
388         mono_counters_register ("Coop Do Blocking", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_do_blocking_count);
389         mono_counters_register ("Coop Do Polling", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_do_polling_count);
390         mono_counters_register ("Coop Save Count", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_save_count);
391         //See the above for what's wrong here.
392
393 #ifdef ENABLE_CHECKED_BUILD_GC
394         mono_native_tls_alloc (&coop_reset_count_stack_key, NULL);
395 #endif
396 }
397
398 void
399 mono_threads_coop_begin_global_suspend (void)
400 {
401         if (mono_threads_is_coop_enabled ())
402                 mono_polling_required = 1;
403 }
404
405 void
406 mono_threads_coop_end_global_suspend (void)
407 {
408         if (mono_threads_is_coop_enabled ())
409                 mono_polling_required = 0;
410 }