Merge pull request #3802 from lambdageek/dev-reference-attr-take3
[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 #include <mono/utils/mono-threads-debug.h>
31
32 #ifdef TARGET_OSX
33 #include <mono/utils/mach-support.h>
34 #endif
35
36 #ifdef _MSC_VER
37 // TODO: Find MSVC replacement for __builtin_unwind_init
38 #define SAVE_REGS_ON_STACK g_assert_not_reached ();
39 #else 
40 #define SAVE_REGS_ON_STACK __builtin_unwind_init ();
41 #endif
42
43 volatile size_t mono_polling_required;
44
45 // FIXME: This would be more efficient if instead of instantiating the stack it just pushed a simple depth counter up and down,
46 // perhaps with a per-thread cookie in the high bits.
47 #ifdef ENABLE_CHECKED_BUILD_GC
48
49 // Maintains a single per-thread stack of ints, used to ensure nesting is not violated
50 static MonoNativeTlsKey coop_reset_count_stack_key;
51
52 static void
53 coop_tls_push (gpointer cookie)
54 {
55         GArray *stack;
56
57         stack = mono_native_tls_get_value (coop_reset_count_stack_key);
58         if (!stack) {
59                 stack = g_array_new (FALSE, FALSE, sizeof(gpointer));
60                 mono_native_tls_set_value (coop_reset_count_stack_key, stack);
61         }
62
63         g_array_append_val (stack, cookie);
64 }
65
66 static void
67 coop_tls_pop (gpointer received_cookie)
68 {
69         GArray *stack;
70         gpointer expected_cookie;
71
72         stack = mono_native_tls_get_value (coop_reset_count_stack_key);
73         if (!stack || 0 == stack->len)
74                 mono_fatal_with_history ("Received cookie %p but found no stack at all\n", received_cookie);
75
76         expected_cookie = g_array_index (stack, gpointer, stack->len - 1);
77         stack->len --;
78
79         if (0 == stack->len) {
80                 g_array_free (stack,TRUE);
81                 mono_native_tls_set_value (coop_reset_count_stack_key, NULL);
82         }
83
84         if (expected_cookie != received_cookie)
85                 mono_fatal_with_history ("Received cookie %p but expected %p\n", received_cookie, expected_cookie);
86 }
87
88 #endif
89
90 static void
91 check_info (MonoThreadInfo *info, const gchar *action, const gchar *state)
92 {
93         if (!info)
94                 g_error ("Cannot %s GC %s region if the thread is not attached", action, state);
95         if (!mono_thread_info_is_current (info))
96                 g_error ("[%p] Cannot %s GC %s region on a different thread", mono_thread_info_get_tid (info), action, state);
97         if (!mono_thread_info_is_live (info))
98                 g_error ("[%p] Cannot %s GC %s region if the thread is not live", mono_thread_info_get_tid (info), action, state);
99 }
100
101 static int coop_reset_blocking_count;
102 static int coop_try_blocking_count;
103 static int coop_do_blocking_count;
104 static int coop_do_polling_count;
105 static int coop_save_count;
106
107 static void
108 mono_threads_state_poll_with_info (MonoThreadInfo *info);
109
110 void
111 mono_threads_state_poll (void)
112 {
113         mono_threads_state_poll_with_info (mono_thread_info_current_unchecked ());
114 }
115
116 static void
117 mono_threads_state_poll_with_info (MonoThreadInfo *info)
118 {
119         g_assert (mono_threads_is_coop_enabled ());
120
121         ++coop_do_polling_count;
122
123         if (!info)
124                 return;
125
126         THREADS_SUSPEND_DEBUG ("FINISH SELF SUSPEND OF %p\n", mono_thread_info_get_tid (info));
127
128         /* Fast check for pending suspend requests */
129         if (!(info->thread_state & (STATE_ASYNC_SUSPEND_REQUESTED | STATE_SELF_SUSPEND_REQUESTED)))
130                 return;
131
132         ++coop_save_count;
133         mono_threads_get_runtime_callbacks ()->thread_state_init (&info->thread_saved_state [SELF_SUSPEND_STATE_INDEX]);
134
135         /* commit the saved state and notify others if needed */
136         switch (mono_threads_transition_state_poll (info)) {
137         case SelfSuspendResumed:
138                 return;
139         case SelfSuspendWait:
140                 mono_thread_info_wait_for_resume (info);
141                 break;
142         case SelfSuspendNotifyAndWait:
143                 mono_threads_notify_initiator_of_suspend (info);
144                 mono_thread_info_wait_for_resume (info);
145                 break;
146         }
147 }
148
149 static volatile gpointer* dummy_global;
150
151 static MONO_NEVER_INLINE
152 void*
153 return_stack_ptr (gpointer *i)
154 {
155         dummy_global = i;
156         return i;
157 }
158
159 static void
160 copy_stack_data (MonoThreadInfo *info, gpointer *stackdata_begin)
161 {
162         MonoThreadUnwindState *state;
163         int stackdata_size;
164         gpointer dummy;
165         void* stackdata_end = return_stack_ptr (&dummy);
166
167         SAVE_REGS_ON_STACK;
168
169         state = &info->thread_saved_state [SELF_SUSPEND_STATE_INDEX];
170
171         stackdata_size = (char*)stackdata_begin - (char*)stackdata_end;
172
173         if (((gsize) stackdata_begin & (SIZEOF_VOID_P - 1)) != 0)
174                 g_error ("stackdata_begin (%p) must be %d-byte aligned", stackdata_begin, SIZEOF_VOID_P);
175         if (((gsize) stackdata_end & (SIZEOF_VOID_P - 1)) != 0)
176                 g_error ("stackdata_end (%p) must be %d-byte aligned", stackdata_end, SIZEOF_VOID_P);
177
178         if (stackdata_size <= 0)
179                 g_error ("stackdata_size = %d, but must be > 0, stackdata_begin = %p, stackdata_end = %p", stackdata_size, stackdata_begin, stackdata_end);
180
181         g_byte_array_set_size (info->stackdata, stackdata_size);
182         state->gc_stackdata = info->stackdata->data;
183         memcpy (state->gc_stackdata, stackdata_end, stackdata_size);
184
185         state->gc_stackdata_size = stackdata_size;
186 }
187
188 static gpointer
189 mono_threads_enter_gc_safe_region_unbalanced_with_info (MonoThreadInfo *info, gpointer *stackdata);
190
191 gpointer
192 mono_threads_enter_gc_safe_region (gpointer *stackdata)
193 {
194         return mono_threads_enter_gc_safe_region_with_info (mono_thread_info_current_unchecked (), stackdata);
195 }
196
197 gpointer
198 mono_threads_enter_gc_safe_region_with_info (MonoThreadInfo *info, gpointer *stackdata)
199 {
200         gpointer cookie;
201
202         if (!mono_threads_is_coop_enabled ())
203                 return NULL;
204
205         cookie = mono_threads_enter_gc_safe_region_unbalanced_with_info (info, stackdata);
206
207 #ifdef ENABLE_CHECKED_BUILD_GC
208         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
209                 coop_tls_push (cookie);
210 #endif
211
212         return cookie;
213 }
214
215 gpointer
216 mono_threads_enter_gc_safe_region_unbalanced (gpointer *stackdata)
217 {
218         return mono_threads_enter_gc_safe_region_unbalanced_with_info (mono_thread_info_current_unchecked (), stackdata);
219 }
220
221 static gpointer
222 mono_threads_enter_gc_safe_region_unbalanced_with_info (MonoThreadInfo *info, gpointer *stackdata)
223 {
224         if (!mono_threads_is_coop_enabled ())
225                 return NULL;
226
227         ++coop_do_blocking_count;
228
229         check_info (info, "enter", "safe");
230
231         copy_stack_data (info, stackdata);
232
233 retry:
234         ++coop_save_count;
235         mono_threads_get_runtime_callbacks ()->thread_state_init (&info->thread_saved_state [SELF_SUSPEND_STATE_INDEX]);
236
237         switch (mono_threads_transition_do_blocking (info)) {
238         case DoBlockingContinue:
239                 break;
240         case DoBlockingPollAndRetry:
241                 mono_threads_state_poll_with_info (info);
242                 goto retry;
243         }
244
245         return info;
246 }
247
248 void
249 mono_threads_exit_gc_safe_region (gpointer cookie, gpointer *stackdata)
250 {
251         if (!mono_threads_is_coop_enabled ())
252                 return;
253
254 #ifdef ENABLE_CHECKED_BUILD_GC
255         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
256                 coop_tls_pop (cookie);
257 #endif
258
259         mono_threads_exit_gc_safe_region_unbalanced (cookie, stackdata);
260 }
261
262 void
263 mono_threads_exit_gc_safe_region_unbalanced (gpointer cookie, gpointer *stackdata)
264 {
265         MonoThreadInfo *info;
266
267         if (!mono_threads_is_coop_enabled ())
268                 return;
269
270         info = (MonoThreadInfo *)cookie;
271
272         check_info (info, "exit", "safe");
273
274         switch (mono_threads_transition_done_blocking (info)) {
275         case DoneBlockingOk:
276                 info->thread_saved_state [SELF_SUSPEND_STATE_INDEX].valid = FALSE;
277                 break;
278         case DoneBlockingWait:
279                 THREADS_SUSPEND_DEBUG ("state polling done, notifying of resume\n");
280                 mono_thread_info_wait_for_resume (info);
281                 break;
282         default:
283                 g_error ("Unknown thread state");
284         }
285 }
286
287 void
288 mono_threads_assert_gc_safe_region (void)
289 {
290         MONO_REQ_GC_SAFE_MODE;
291 }
292
293 gpointer
294 mono_threads_enter_gc_unsafe_region (gpointer *stackdata)
295 {
296         return mono_threads_enter_gc_unsafe_region_with_info (mono_thread_info_current_unchecked (), stackdata);
297 }
298
299 gpointer
300 mono_threads_enter_gc_unsafe_region_with_info (THREAD_INFO_TYPE *info, gpointer *stackdata)
301 {
302         gpointer cookie;
303
304         if (!mono_threads_is_coop_enabled ())
305                 return NULL;
306
307         cookie = mono_threads_enter_gc_unsafe_region_unbalanced_with_info (info, stackdata);
308
309 #ifdef ENABLE_CHECKED_BUILD_GC
310         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
311                 coop_tls_push (cookie);
312 #endif
313
314         return cookie;
315 }
316
317 gpointer
318 mono_threads_enter_gc_unsafe_region_unbalanced (gpointer *stackdata)
319 {
320         return mono_threads_enter_gc_unsafe_region_unbalanced_with_info (mono_thread_info_current_unchecked (), stackdata);
321 }
322
323 gpointer
324 mono_threads_enter_gc_unsafe_region_unbalanced_with_info (MonoThreadInfo *info, gpointer *stackdata)
325 {
326         if (!mono_threads_is_coop_enabled ())
327                 return NULL;
328
329         ++coop_reset_blocking_count;
330
331         check_info (info, "enter", "unsafe");
332
333         copy_stack_data (info, stackdata);
334
335         switch (mono_threads_transition_abort_blocking (info)) {
336         case AbortBlockingIgnore:
337                 info->thread_saved_state [SELF_SUSPEND_STATE_INDEX].valid = FALSE;
338                 return NULL;
339         case AbortBlockingIgnoreAndPoll:
340                 mono_threads_state_poll_with_info (info);
341                 return NULL;
342         case AbortBlockingOk:
343                 info->thread_saved_state [SELF_SUSPEND_STATE_INDEX].valid = FALSE;
344                 break;
345         case AbortBlockingWait:
346                 mono_thread_info_wait_for_resume (info);
347                 break;
348         default:
349                 g_error ("Unknown thread state");
350         }
351
352         return info;
353 }
354
355 gpointer
356 mono_threads_enter_gc_unsafe_region_cookie (void)
357 {
358         MonoThreadInfo *info;
359
360         g_assert (mono_threads_is_coop_enabled ());
361
362         info = mono_thread_info_current_unchecked ();
363
364         check_info (info, "enter (cookie)", "unsafe");
365
366 #ifdef ENABLE_CHECKED_BUILD_GC
367         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
368                 coop_tls_push (info);
369 #endif
370
371         return info;
372 }
373
374 void
375 mono_threads_exit_gc_unsafe_region (gpointer cookie, gpointer *stackdata)
376 {
377         if (!mono_threads_is_coop_enabled ())
378                 return;
379
380 #ifdef ENABLE_CHECKED_BUILD_GC
381         if (mono_check_mode_enabled (MONO_CHECK_MODE_GC))
382                 coop_tls_pop (cookie);
383 #endif
384
385         mono_threads_exit_gc_unsafe_region_unbalanced (cookie, stackdata);
386 }
387
388 void
389 mono_threads_exit_gc_unsafe_region_unbalanced (gpointer cookie, gpointer *stackdata)
390 {
391         if (!mono_threads_is_coop_enabled ())
392                 return;
393
394         if (!cookie)
395                 return;
396
397         mono_threads_enter_gc_safe_region_unbalanced (stackdata);
398 }
399
400 void
401 mono_threads_assert_gc_unsafe_region (void)
402 {
403         MONO_REQ_GC_UNSAFE_MODE;
404 }
405
406 gboolean
407 mono_threads_is_coop_enabled (void)
408 {
409 #if defined(USE_COOP_GC)
410         return TRUE;
411 #else
412         static int is_coop_enabled = -1;
413         if (G_UNLIKELY (is_coop_enabled == -1))
414                 is_coop_enabled = g_getenv ("MONO_ENABLE_COOP") != NULL ? 1 : 0;
415         return is_coop_enabled == 1;
416 #endif
417 }
418
419
420 void
421 mono_threads_coop_init (void)
422 {
423         if (!mono_threads_is_coop_enabled ())
424                 return;
425
426         mono_counters_register ("Coop Reset Blocking", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_reset_blocking_count);
427         mono_counters_register ("Coop Try Blocking", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_try_blocking_count);
428         mono_counters_register ("Coop Do Blocking", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_do_blocking_count);
429         mono_counters_register ("Coop Do Polling", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_do_polling_count);
430         mono_counters_register ("Coop Save Count", MONO_COUNTER_GC | MONO_COUNTER_INT, &coop_save_count);
431         //See the above for what's wrong here.
432
433 #ifdef ENABLE_CHECKED_BUILD_GC
434         mono_native_tls_alloc (&coop_reset_count_stack_key, NULL);
435 #endif
436 }
437
438 void
439 mono_threads_coop_begin_global_suspend (void)
440 {
441         if (mono_threads_is_coop_enabled ())
442                 mono_polling_required = 1;
443 }
444
445 void
446 mono_threads_coop_end_global_suspend (void)
447 {
448         if (mono_threads_is_coop_enabled ())
449                 mono_polling_required = 0;
450 }