2 * mono-threads.c: Low-level threading
5 * Rodrigo Kumpera (kumpera@gmail.com)
7 * Copyright 2011 Novell, Inc (http://www.novell.com)
8 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11 #include <mono/utils/mono-compiler.h>
12 #include <mono/utils/mono-semaphore.h>
13 #include <mono/utils/mono-threads.h>
14 #include <mono/utils/mono-tls.h>
15 #include <mono/utils/hazard-pointer.h>
16 #include <mono/utils/mono-memory-model.h>
17 #include <mono/metadata/appdomain.h>
18 #include <mono/metadata/domain-internals.h>
23 #include <mono/utils/mach-support.h>
26 #define THREADS_DEBUG(...)
27 //#define THREADS_DEBUG(...) g_message(__VA_ARGS__)
30 Mutex that makes sure only a single thread can be suspending others.
31 Suspend is a very racy operation since it requires restarting until
32 the target thread is not on an unsafe region.
34 We could implement this using critical regions, but would be much much
35 harder for an operation that is hardly performance critical.
37 The GC has to acquire this lock before starting a STW to make sure
38 a runtime suspend won't make it wronly see a thread in a safepoint
39 when it is in fact not.
41 static MonoSemType global_suspend_semaphore;
43 static int thread_info_size;
44 static MonoThreadInfoCallbacks threads_callbacks;
45 static MonoThreadInfoRuntimeCallbacks runtime_callbacks;
46 static MonoNativeTlsKey thread_info_key, small_id_key;
47 static MonoLinkedListSet thread_list;
48 static gboolean disable_new_interrupt = FALSE;
49 static gboolean mono_threads_inited = FALSE;
51 static void mono_threads_unregister_current_thread (MonoThreadInfo *info);
55 mono_hazard_pointer_clear_all (MonoThreadHazardPointers *hp, int retain)
58 mono_hazard_pointer_clear (hp, 0);
60 mono_hazard_pointer_clear (hp, 1);
62 mono_hazard_pointer_clear (hp, 2);
66 If return non null Hazard Pointer 1 holds the return value.
69 mono_thread_info_lookup (MonoNativeThreadId id)
71 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
73 if (!mono_lls_find (&thread_list, hp, (uintptr_t)id)) {
74 mono_hazard_pointer_clear_all (hp, -1);
78 mono_hazard_pointer_clear_all (hp, 1);
79 return mono_hazard_pointer_get_val (hp, 1);
83 mono_thread_info_insert (MonoThreadInfo *info)
85 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
87 if (!mono_lls_insert (&thread_list, hp, (MonoLinkedListSetNode*)info)) {
88 mono_hazard_pointer_clear_all (hp, -1);
92 mono_hazard_pointer_clear_all (hp, -1);
97 mono_thread_info_remove (MonoThreadInfo *info)
99 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
102 THREADS_DEBUG ("removing info %p\n", info);
103 res = mono_lls_remove (&thread_list, hp, (MonoLinkedListSetNode*)info);
104 mono_hazard_pointer_clear_all (hp, -1);
109 free_thread_info (gpointer mem)
111 MonoThreadInfo *info = mem;
113 MONO_SEM_DESTROY (&info->suspend_semaphore);
114 MONO_SEM_DESTROY (&info->resume_semaphore);
115 MONO_SEM_DESTROY (&info->finish_resume_semaphore);
116 mono_threads_platform_free (info);
122 mono_thread_info_register_small_id (void)
124 int small_id = mono_thread_small_id_alloc ();
125 mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (small_id + 1));
130 register_thread (MonoThreadInfo *info, gpointer baseptr)
132 int small_id = mono_thread_info_register_small_id ();
134 mono_thread_info_set_tid (info, mono_native_thread_id_get ());
135 info->small_id = small_id;
137 MONO_SEM_INIT (&info->suspend_semaphore, 1);
138 MONO_SEM_INIT (&info->resume_semaphore, 0);
139 MONO_SEM_INIT (&info->finish_resume_semaphore, 0);
141 /*set TLS early so SMR works */
142 mono_native_tls_set_value (thread_info_key, info);
144 THREADS_DEBUG ("registering info %p tid %p small id %x\n", info, mono_thread_info_get_tid (info), info->small_id);
146 if (threads_callbacks.thread_register) {
147 if (threads_callbacks.thread_register (info, baseptr) == NULL) {
148 g_warning ("thread registation failed\n");
154 mono_threads_platform_register (info);
155 info->thread_state = STATE_RUNNING;
156 mono_thread_info_suspend_lock ();
157 /*If this fail it means a given thread has been registered twice, which doesn't make sense. */
158 result = mono_thread_info_insert (info);
160 mono_thread_info_suspend_unlock ();
165 unregister_thread (void *arg)
167 MonoThreadInfo *info = arg;
168 int small_id = info->small_id;
171 THREADS_DEBUG ("unregistering info %p\n", info);
174 * TLS destruction order is not reliable so small_id might be cleaned up
177 mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (info->small_id + 1));
179 info->thread_state = STATE_SHUTTING_DOWN;
182 First perform the callback that requires no locks.
183 This callback has the potential of taking other locks, so we do it before.
184 After it completes, the thread remains functional.
186 if (threads_callbacks.thread_detach)
187 threads_callbacks.thread_detach (info);
189 mono_thread_info_suspend_lock ();
192 Now perform the callback that must be done under locks.
193 This will render the thread useless and non-suspendable, so it must
194 be done while holding the suspend lock to give no other thread chance
197 if (threads_callbacks.thread_unregister)
198 threads_callbacks.thread_unregister (info);
199 mono_threads_unregister_current_thread (info);
201 info->thread_state = STATE_DEAD;
202 mono_thread_info_suspend_unlock ();
204 /*now it's safe to free the thread info.*/
205 mono_thread_hazardous_free_or_queue (info, free_thread_info, TRUE, FALSE);
206 mono_thread_small_id_free (small_id);
210 * Removes the current thread from the thread list.
211 * This must be called from the thread unregister callback and nowhere else.
212 * The current thread must be passed as TLS might have already been cleaned up.
215 mono_threads_unregister_current_thread (MonoThreadInfo *info)
218 g_assert (mono_thread_info_get_tid (info) == mono_native_thread_id_get ());
219 result = mono_thread_info_remove (info);
224 mono_thread_info_current (void)
226 MonoThreadInfo *info = (MonoThreadInfo*)mono_native_tls_get_value (thread_info_key);
230 info = mono_thread_info_lookup (mono_native_thread_id_get ()); /*info on HP1*/
233 We might be called during thread cleanup, but we cannot be called after cleanup as happened.
234 The way to distinguish between before, during and after cleanup is the following:
236 -If the TLS key is set, cleanup has not begun;
237 -If the TLS key is clean, but the thread remains registered, cleanup is in progress;
238 -If the thread is nowhere to be found, cleanup has finished.
240 We cannot function after cleanup since there's no way to ensure what will happen.
244 /*We're looking up the current thread which will not be freed until we finish running, so no need to keep it on a HP */
245 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
251 mono_thread_info_get_small_id (void)
253 gpointer val = mono_native_tls_get_value (small_id_key);
256 return GPOINTER_TO_INT (val) - 1;
260 mono_thread_info_list_head (void)
266 mono_thread_info_attach (void *baseptr)
268 MonoThreadInfo *info;
269 if (!mono_threads_inited)
271 /* This can happen from DllMain(DLL_THREAD_ATTACH) on Windows, if a
272 * thread is created before an embedding API user initialized Mono. */
273 THREADS_DEBUG ("mono_thread_info_attach called before mono_threads_init\n");
276 info = mono_native_tls_get_value (thread_info_key);
278 info = g_malloc0 (thread_info_size);
279 THREADS_DEBUG ("attaching %p\n", info);
280 if (!register_thread (info, baseptr))
282 } else if (threads_callbacks.thread_attach) {
283 threads_callbacks.thread_attach (info);
289 mono_thread_info_dettach (void)
291 MonoThreadInfo *info;
292 if (!mono_threads_inited)
294 /* This can happen from DllMain(THREAD_DETACH) on Windows, if a thread
295 * is created before an embedding API user initialized Mono. */
296 THREADS_DEBUG ("mono_thread_info_dettach called before mono_threads_init\n");
299 info = mono_native_tls_get_value (thread_info_key);
301 THREADS_DEBUG ("detaching %p\n", info);
302 unregister_thread (info);
303 mono_native_tls_set_value (thread_info_key, NULL);
308 mono_threads_init (MonoThreadInfoCallbacks *callbacks, size_t info_size)
311 threads_callbacks = *callbacks;
312 thread_info_size = info_size;
314 res = mono_native_tls_alloc (&thread_info_key, NULL);
316 res = mono_native_tls_alloc (&thread_info_key, unregister_thread);
320 res = mono_native_tls_alloc (&small_id_key, NULL);
323 MONO_SEM_INIT (&global_suspend_semaphore, 1);
325 mono_lls_init (&thread_list, NULL);
326 mono_thread_smr_init ();
327 mono_threads_init_platform ();
329 #if defined(__MACH__)
330 mono_mach_init (thread_info_key);
333 mono_threads_inited = TRUE;
335 g_assert (sizeof (MonoNativeThreadId) <= sizeof (uintptr_t));
339 mono_threads_runtime_init (MonoThreadInfoRuntimeCallbacks *callbacks)
341 runtime_callbacks = *callbacks;
344 MonoThreadInfoCallbacks *
345 mono_threads_get_callbacks (void)
347 return &threads_callbacks;
350 MonoThreadInfoRuntimeCallbacks *
351 mono_threads_get_runtime_callbacks (void)
353 return &runtime_callbacks;
357 The return value is only valid until a matching mono_thread_info_resume is called
359 static MonoThreadInfo*
360 mono_thread_info_suspend_sync (MonoNativeThreadId tid, gboolean interrupt_kernel)
362 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
363 MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
367 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
369 /*thread is on the process of detaching*/
370 if (mono_thread_info_run_state (info) > STATE_RUNNING) {
371 mono_hazard_pointer_clear (hp, 1);
375 THREADS_DEBUG ("suspend %x IN COUNT %d\n", tid, info->suspend_count);
377 if (info->suspend_count) {
378 ++info->suspend_count;
379 mono_hazard_pointer_clear (hp, 1);
380 MONO_SEM_POST (&info->suspend_semaphore);
384 if (!mono_threads_core_suspend (info)) {
385 MONO_SEM_POST (&info->suspend_semaphore);
386 mono_hazard_pointer_clear (hp, 1);
390 if (interrupt_kernel)
391 mono_threads_core_interrupt (info);
393 ++info->suspend_count;
394 info->thread_state |= STATE_SUSPENDED;
395 MONO_SEM_POST (&info->suspend_semaphore);
396 mono_hazard_pointer_clear (hp, 1);
402 mono_thread_info_self_suspend (void)
405 MonoThreadInfo *info = mono_thread_info_current ();
409 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
411 THREADS_DEBUG ("self suspend IN COUNT %d\n", info->suspend_count);
413 g_assert (info->suspend_count == 0);
414 ++info->suspend_count;
416 info->thread_state |= STATE_SELF_SUSPENDED;
418 ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&info->suspend_state, NULL);
421 MONO_SEM_POST (&info->suspend_semaphore);
423 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->resume_semaphore);
425 g_assert (!info->async_target); /*FIXME this should happen normally for suspend. */
426 MONO_SEM_POST (&info->finish_resume_semaphore);
430 mono_thread_info_resume_internal (MonoThreadInfo *info)
433 if (mono_thread_info_suspend_state (info) == STATE_SELF_SUSPENDED) {
434 MONO_SEM_POST (&info->resume_semaphore);
435 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->finish_resume_semaphore);
438 result = mono_threads_core_resume (info);
440 info->thread_state &= ~SUSPEND_STATE_MASK;
445 mono_thread_info_resume (MonoNativeThreadId tid)
447 gboolean result = TRUE;
448 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
449 MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
453 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
455 THREADS_DEBUG ("resume %x IN COUNT %d\n",tid, info->suspend_count);
457 if (info->suspend_count <= 0) {
458 MONO_SEM_POST (&info->suspend_semaphore);
459 mono_hazard_pointer_clear (hp, 1);
464 * The theory here is that if we manage to suspend the thread it means it did not
465 * start cleanup since it take the same lock.
467 g_assert (mono_thread_info_get_tid (info));
469 if (--info->suspend_count == 0)
470 result = mono_thread_info_resume_internal (info);
472 MONO_SEM_POST (&info->suspend_semaphore);
473 mono_hazard_pointer_clear (hp, 1);
474 mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, FALSE);
480 mono_thread_info_finish_suspend (void)
482 mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, FALSE);
486 FIXME fix cardtable WB to be out of line and check with the runtime if the target is not the
487 WB trampoline. Another option is to encode wb ranges in MonoJitInfo, but that is somewhat hard.
490 is_thread_in_critical_region (MonoThreadInfo *info)
495 if (info->inside_critical_region)
498 ji = mono_jit_info_table_find (
499 info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
500 MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
505 method = mono_jit_info_get_method (ji);
507 return threads_callbacks.mono_method_is_critical (method);
512 If we are trying to suspend a target that is on a critical region
513 and running a syscall we risk looping forever if @interrupt_kernel is FALSE.
514 So, be VERY carefull in calling this with @interrupt_kernel == FALSE.
517 mono_thread_info_safe_suspend_sync (MonoNativeThreadId id, gboolean interrupt_kernel)
519 MonoThreadInfo *info = NULL;
520 int sleep_duration = 0;
522 /*FIXME: unify this with self-suspend*/
523 g_assert (id != mono_native_thread_id_get ());
525 mono_thread_info_suspend_lock ();
528 if (!(info = mono_thread_info_suspend_sync (id, interrupt_kernel))) {
529 g_warning ("failed to suspend thread %p, hopefully it is dead", (gpointer)id);
530 mono_thread_info_suspend_unlock ();
533 /*WARNING: We now are in interrupt context until we resume the thread. */
534 if (!is_thread_in_critical_region (info))
537 if (!mono_thread_info_resume (id)) {
538 g_warning ("failed to result thread %p, hopefully it is dead", (gpointer)id);
539 mono_thread_info_suspend_unlock ();
542 THREADS_DEBUG ("restarted thread %p\n", (gpointer)id);
544 if (!sleep_duration) {
552 g_usleep (sleep_duration);
554 sleep_duration += 10;
557 mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, TRUE);
559 mono_thread_info_suspend_unlock ();
564 Inject an assynchronous call into the target thread. The target thread must be suspended and
565 only a single async call can be setup for a given suspend cycle.
566 This async call must cause stack unwinding as the current implementation doesn't save enough state
567 to resume execution of the top-of-stack function. It's an acceptable limitation since this is
568 currently used only to deliver exceptions.
571 mono_thread_info_setup_async_call (MonoThreadInfo *info, void (*target_func)(void*), void *user_data)
573 g_assert (info->suspend_count);
574 /*FIXME this is a bad assert, we probably should do proper locking and fail if one is already set*/
575 g_assert (!info->async_target);
576 info->async_target = target_func;
577 /* This is not GC tracked */
578 info->user_data = user_data;
582 The suspend lock is held during any suspend in progress.
583 A GC that has safepoints must take this lock as part of its
584 STW to make sure no unsafe pending suspend is in progress.
587 mono_thread_info_suspend_lock (void)
589 MONO_SEM_WAIT_UNITERRUPTIBLE (&global_suspend_semaphore);
593 mono_thread_info_suspend_unlock (void)
595 MONO_SEM_POST (&global_suspend_semaphore);
599 mono_thread_info_disable_new_interrupt (gboolean disable)
601 disable_new_interrupt = disable;
605 * This is a very specific function whose only purpose is to
606 * break a given thread from socket syscalls.
608 * This only exists because linux won't fail a call to connect
609 * if the underlying is closed.
611 * TODO We should cleanup and unify this with the other syscall abort
615 mono_thread_info_abort_socket_syscall_for_close (MonoNativeThreadId tid)
617 MonoThreadHazardPointers *hp;
618 MonoThreadInfo *info;
620 if (tid == mono_native_thread_id_get () || !mono_threads_core_needs_abort_syscall ())
623 hp = mono_hazard_pointer_get ();
624 info = mono_thread_info_lookup (tid); /*info on HP1*/
628 if (mono_thread_info_run_state (info) > STATE_RUNNING) {
629 mono_hazard_pointer_clear (hp, 1);
633 mono_thread_info_suspend_lock ();
635 mono_threads_core_abort_syscall (info);
637 mono_hazard_pointer_clear (hp, 1);
638 mono_thread_info_suspend_unlock ();
642 Disabled by default for now.
643 To enable this we need mini to implement the callbacks by MonoThreadInfoRuntimeCallbacks
644 which means mono-context and setup_async_callback, and we need a mono-threads backend.
647 mono_thread_info_new_interrupt_enabled (void)
649 /*We need STW gc events to work correctly*/
650 #if defined (HAVE_BOEHM_GC) && !defined (USE_INCLUDED_LIBGC)
654 #if defined(HOST_WIN32)
657 #if defined (__i386__)
658 return !disable_new_interrupt;
664 * mono_thread_info_set_is_async_context:
666 * Set whenever the current thread is in an async context. Some runtime functions might behave
667 * differently while in an async context in order to be async safe.
670 mono_thread_info_set_is_async_context (gboolean async_context)
672 MonoThreadInfo *info = mono_thread_info_current ();
675 info->is_async_context = async_context;
679 mono_thread_info_is_async_context (void)
681 MonoThreadInfo *info = mono_thread_info_current ();
684 return info->is_async_context;