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>
21 #include <mono/utils/mach-support.h>
24 #define THREADS_DEBUG(...)
25 //#define THREADS_DEBUG(...) g_message(__VA_ARGS__)
28 Mutex that makes sure only a single thread can be suspending others.
29 Suspend is a very racy operation since it requires restarting until
30 the target thread is not on an unsafe region.
32 We could implement this using critical regions, but would be much much
33 harder for an operation that is hardly performance critical.
35 The GC has to acquire this lock before starting a STW to make sure
36 a runtime suspend won't make it wronly see a thread in a safepoint
37 when it is in fact not.
39 static MonoSemType global_suspend_semaphore;
41 static size_t thread_info_size;
42 static MonoThreadInfoCallbacks threads_callbacks;
43 static MonoThreadInfoRuntimeCallbacks runtime_callbacks;
44 static MonoNativeTlsKey thread_info_key, thread_exited_key, small_id_key;
45 static MonoLinkedListSet thread_list;
46 static gboolean disable_new_interrupt = FALSE;
47 static gboolean mono_threads_inited = FALSE;
49 static void mono_threads_unregister_current_thread (MonoThreadInfo *info);
53 mono_hazard_pointer_clear_all (MonoThreadHazardPointers *hp, int retain)
56 mono_hazard_pointer_clear (hp, 0);
58 mono_hazard_pointer_clear (hp, 1);
60 mono_hazard_pointer_clear (hp, 2);
64 If return non null Hazard Pointer 1 holds the return value.
67 mono_thread_info_lookup (MonoNativeThreadId id)
69 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
71 if (!mono_lls_find (&thread_list, hp, (uintptr_t)id)) {
72 mono_hazard_pointer_clear_all (hp, -1);
76 mono_hazard_pointer_clear_all (hp, 1);
77 return mono_hazard_pointer_get_val (hp, 1);
81 mono_thread_info_insert (MonoThreadInfo *info)
83 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
85 if (!mono_lls_insert (&thread_list, hp, (MonoLinkedListSetNode*)info)) {
86 mono_hazard_pointer_clear_all (hp, -1);
90 mono_hazard_pointer_clear_all (hp, -1);
95 mono_thread_info_remove (MonoThreadInfo *info)
97 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
100 THREADS_DEBUG ("removing info %p\n", info);
101 res = mono_lls_remove (&thread_list, hp, (MonoLinkedListSetNode*)info);
102 mono_hazard_pointer_clear_all (hp, -1);
107 free_thread_info (gpointer mem)
109 MonoThreadInfo *info = mem;
111 MONO_SEM_DESTROY (&info->suspend_semaphore);
112 MONO_SEM_DESTROY (&info->resume_semaphore);
113 MONO_SEM_DESTROY (&info->finish_resume_semaphore);
114 mono_threads_platform_free (info);
120 mono_thread_info_register_small_id (void)
122 int small_id = mono_thread_small_id_alloc ();
123 mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (small_id + 1));
128 register_thread (MonoThreadInfo *info, gpointer baseptr)
130 int small_id = mono_thread_info_register_small_id ();
132 mono_thread_info_set_tid (info, mono_native_thread_id_get ());
133 info->small_id = small_id;
135 MONO_SEM_INIT (&info->suspend_semaphore, 1);
136 MONO_SEM_INIT (&info->resume_semaphore, 0);
137 MONO_SEM_INIT (&info->finish_resume_semaphore, 0);
139 /*set TLS early so SMR works */
140 mono_native_tls_set_value (thread_info_key, info);
142 THREADS_DEBUG ("registering info %p tid %p small id %x\n", info, mono_thread_info_get_tid (info), info->small_id);
144 if (threads_callbacks.thread_register) {
145 if (threads_callbacks.thread_register (info, baseptr) == NULL) {
146 g_warning ("thread registation failed\n");
152 mono_threads_platform_register (info);
153 info->thread_state = STATE_RUNNING;
154 mono_thread_info_suspend_lock ();
155 /*If this fail it means a given thread has been registered twice, which doesn't make sense. */
156 result = mono_thread_info_insert (info);
158 mono_thread_info_suspend_unlock ();
163 unregister_thread (void *arg)
165 MonoThreadInfo *info = arg;
166 int small_id = info->small_id;
169 THREADS_DEBUG ("unregistering info %p\n", info);
171 mono_native_tls_set_value (thread_exited_key, GUINT_TO_POINTER (1));
173 mono_threads_core_unregister (info);
176 * TLS destruction order is not reliable so small_id might be cleaned up
179 mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (info->small_id + 1));
181 info->thread_state = STATE_SHUTTING_DOWN;
184 First perform the callback that requires no locks.
185 This callback has the potential of taking other locks, so we do it before.
186 After it completes, the thread remains functional.
188 if (threads_callbacks.thread_detach)
189 threads_callbacks.thread_detach (info);
191 mono_thread_info_suspend_lock ();
194 Now perform the callback that must be done under locks.
195 This will render the thread useless and non-suspendable, so it must
196 be done while holding the suspend lock to give no other thread chance
199 if (threads_callbacks.thread_unregister)
200 threads_callbacks.thread_unregister (info);
201 mono_threads_unregister_current_thread (info);
203 info->thread_state = STATE_DEAD;
204 mono_thread_info_suspend_unlock ();
206 /*now it's safe to free the thread info.*/
207 mono_thread_hazardous_free_or_queue (info, free_thread_info, TRUE, FALSE);
208 mono_thread_small_id_free (small_id);
212 thread_exited_dtor (void *arg)
214 #if defined(__MACH__)
216 * Since we use pthread dtors to clean up thread data, if a thread
217 * is attached to the runtime by another pthread dtor after our dtor
218 * has ran, it will never be detached, leading to various problems
219 * since the thread ids etc. will be reused while they are still in
220 * the threads hashtables etc.
221 * Dtors are called in a loop until all user tls entries are 0,
222 * but the loop has a maximum count (4), so if we set the tls
223 * variable every time, it will remain set when system tls dtors
224 * are ran. This allows mono_thread_info_is_exiting () to detect
225 * whenever the thread is exiting, even if it is executed from a
226 * system tls dtor (i.e. obj-c dealloc methods).
228 mono_native_tls_set_value (thread_exited_key, GUINT_TO_POINTER (1));
233 * Removes the current thread from the thread list.
234 * This must be called from the thread unregister callback and nowhere else.
235 * The current thread must be passed as TLS might have already been cleaned up.
238 mono_threads_unregister_current_thread (MonoThreadInfo *info)
241 g_assert (mono_thread_info_get_tid (info) == mono_native_thread_id_get ());
242 result = mono_thread_info_remove (info);
247 mono_thread_info_current (void)
249 MonoThreadInfo *info = (MonoThreadInfo*)mono_native_tls_get_value (thread_info_key);
253 info = mono_thread_info_lookup (mono_native_thread_id_get ()); /*info on HP1*/
256 We might be called during thread cleanup, but we cannot be called after cleanup as happened.
257 The way to distinguish between before, during and after cleanup is the following:
259 -If the TLS key is set, cleanup has not begun;
260 -If the TLS key is clean, but the thread remains registered, cleanup is in progress;
261 -If the thread is nowhere to be found, cleanup has finished.
263 We cannot function after cleanup since there's no way to ensure what will happen.
267 /*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 */
268 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
274 mono_thread_info_get_small_id (void)
276 gpointer val = mono_native_tls_get_value (small_id_key);
279 return GPOINTER_TO_INT (val) - 1;
283 mono_thread_info_list_head (void)
289 mono_thread_info_attach (void *baseptr)
291 MonoThreadInfo *info;
292 if (!mono_threads_inited)
294 /* This can happen from DllMain(DLL_THREAD_ATTACH) on Windows, if a
295 * thread is created before an embedding API user initialized Mono. */
296 THREADS_DEBUG ("mono_thread_info_attach called before mono_threads_init\n");
299 info = mono_native_tls_get_value (thread_info_key);
301 info = g_malloc0 (thread_info_size);
302 THREADS_DEBUG ("attaching %p\n", info);
303 if (!register_thread (info, baseptr))
305 } else if (threads_callbacks.thread_attach) {
306 threads_callbacks.thread_attach (info);
312 mono_thread_info_detach (void)
314 MonoThreadInfo *info;
315 if (!mono_threads_inited)
317 /* This can happen from DllMain(THREAD_DETACH) on Windows, if a thread
318 * is created before an embedding API user initialized Mono. */
319 THREADS_DEBUG ("mono_thread_info_detach called before mono_threads_init\n");
322 info = mono_native_tls_get_value (thread_info_key);
324 THREADS_DEBUG ("detaching %p\n", info);
325 unregister_thread (info);
326 mono_native_tls_set_value (thread_info_key, NULL);
331 * mono_thread_info_is_exiting:
333 * Return whenever the current thread is exiting, i.e. it is running pthread
337 mono_thread_info_is_exiting (void)
339 #if defined(__MACH__)
340 if (mono_native_tls_get_value (thread_exited_key) == GUINT_TO_POINTER (1))
347 mono_threads_init (MonoThreadInfoCallbacks *callbacks, size_t info_size)
350 threads_callbacks = *callbacks;
351 thread_info_size = info_size;
353 res = mono_native_tls_alloc (&thread_info_key, NULL);
354 res = mono_native_tls_alloc (&thread_exited_key, NULL);
356 res = mono_native_tls_alloc (&thread_info_key, unregister_thread);
357 res = mono_native_tls_alloc (&thread_exited_key, thread_exited_dtor);
361 res = mono_native_tls_alloc (&small_id_key, NULL);
364 MONO_SEM_INIT (&global_suspend_semaphore, 1);
366 mono_lls_init (&thread_list, NULL);
367 mono_thread_smr_init ();
368 mono_threads_init_platform ();
370 #if defined(__MACH__)
371 mono_mach_init (thread_info_key);
374 mono_threads_inited = TRUE;
376 g_assert (sizeof (MonoNativeThreadId) <= sizeof (uintptr_t));
380 mono_threads_runtime_init (MonoThreadInfoRuntimeCallbacks *callbacks)
382 runtime_callbacks = *callbacks;
385 MonoThreadInfoCallbacks *
386 mono_threads_get_callbacks (void)
388 return &threads_callbacks;
391 MonoThreadInfoRuntimeCallbacks *
392 mono_threads_get_runtime_callbacks (void)
394 return &runtime_callbacks;
398 The return value is only valid until a matching mono_thread_info_resume is called
400 static MonoThreadInfo*
401 mono_thread_info_suspend_sync (MonoNativeThreadId tid, gboolean interrupt_kernel, const char **error_condition)
403 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
404 MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
406 *error_condition = "Thread not found";
410 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
412 /*thread is on the process of detaching*/
413 if (mono_thread_info_run_state (info) > STATE_RUNNING) {
414 mono_hazard_pointer_clear (hp, 1);
415 *error_condition = "Thread is detaching";
419 THREADS_DEBUG ("suspend %x IN COUNT %d\n", tid, info->suspend_count);
421 if (info->suspend_count) {
422 ++info->suspend_count;
423 mono_hazard_pointer_clear (hp, 1);
424 MONO_SEM_POST (&info->suspend_semaphore);
428 if (!mono_threads_core_suspend (info)) {
429 MONO_SEM_POST (&info->suspend_semaphore);
430 mono_hazard_pointer_clear (hp, 1);
431 *error_condition = "Could not suspend thread";
435 if (interrupt_kernel)
436 mono_threads_core_interrupt (info);
438 ++info->suspend_count;
439 info->thread_state |= STATE_SUSPENDED;
440 MONO_SEM_POST (&info->suspend_semaphore);
446 mono_thread_info_self_suspend (void)
449 MonoThreadInfo *info = mono_thread_info_current ();
453 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
455 THREADS_DEBUG ("self suspend IN COUNT %d\n", info->suspend_count);
457 g_assert (info->suspend_count == 0);
458 ++info->suspend_count;
460 info->thread_state |= STATE_SELF_SUSPENDED;
462 ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&info->suspend_state, NULL);
465 MONO_SEM_POST (&info->suspend_semaphore);
467 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->resume_semaphore);
469 g_assert (!info->async_target); /*FIXME this should happen normally for suspend. */
470 MONO_SEM_POST (&info->finish_resume_semaphore);
474 mono_thread_info_core_resume (MonoThreadInfo *info)
477 MonoNativeThreadId tid = mono_thread_info_get_tid (info);
478 if (info->create_suspended) {
479 /* Have to special case this, as the normal suspend/resume pair are racy, they don't work if he resume is received before the suspend */
480 info->create_suspended = FALSE;
481 mono_threads_core_resume_created (info, tid);
485 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
487 THREADS_DEBUG ("resume %x IN COUNT %d\n", tid, info->suspend_count);
489 if (info->suspend_count <= 0) {
490 MONO_SEM_POST (&info->suspend_semaphore);
495 * The theory here is that if we manage to suspend the thread it means it did not
496 * start cleanup since it take the same lock.
498 g_assert (mono_thread_info_get_tid (info));
500 if (--info->suspend_count == 0) {
501 if (mono_thread_info_suspend_state (info) == STATE_SELF_SUSPENDED) {
502 MONO_SEM_POST (&info->resume_semaphore);
503 MONO_SEM_WAIT_UNITERRUPTIBLE (&info->finish_resume_semaphore);
506 result = mono_threads_core_resume (info);
508 info->thread_state &= ~SUSPEND_STATE_MASK;
513 MONO_SEM_POST (&info->suspend_semaphore);
518 mono_thread_info_resume (MonoNativeThreadId tid)
520 gboolean result; /* don't initialize it so the compiler can catch unitilized paths. */
521 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
522 MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
528 result = mono_thread_info_core_resume (info);
531 mono_hazard_pointer_clear (hp, 1);
536 mono_thread_info_finish_suspend (MonoThreadInfo *info)
538 mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, FALSE);
542 mono_thread_info_finish_suspend_and_resume (MonoThreadInfo *info)
544 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
546 /*Resume can access info after the target has resumed, so we must ensure it won't touch freed memory. */
547 mono_hazard_pointer_set (hp, 1, info);
548 mono_thread_info_core_resume (info);
549 mono_hazard_pointer_clear (hp, 1);
551 mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, FALSE);
555 FIXME fix cardtable WB to be out of line and check with the runtime if the target is not the
556 WB trampoline. Another option is to encode wb ranges in MonoJitInfo, but that is somewhat hard.
559 is_thread_in_critical_region (MonoThreadInfo *info)
564 if (info->inside_critical_region)
567 /* The target thread might be shutting down and the domain might be null, which means no managed code left to run. */
568 if (!info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN])
571 ji = mono_jit_info_table_find (
572 info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
573 MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
578 method = mono_jit_info_get_method (ji);
580 return threads_callbacks.mono_method_is_critical (method);
585 If we are trying to suspend a target that is on a critical region
586 and running a syscall we risk looping forever if @interrupt_kernel is FALSE.
587 So, be VERY carefull in calling this with @interrupt_kernel == FALSE.
589 Info is not put on a hazard pointer as a suspended thread cannot exit and be freed.
591 This function MUST be matched with mono_thread_info_finish_suspend or mono_thread_info_finish_suspend_and_resume
594 mono_thread_info_safe_suspend_sync (MonoNativeThreadId id, gboolean interrupt_kernel)
596 MonoThreadInfo *info = NULL;
597 int sleep_duration = 0;
599 /*FIXME: unify this with self-suspend*/
600 g_assert (id != mono_native_thread_id_get ());
602 mono_thread_info_suspend_lock ();
605 const char *suspend_error = "Unknown error";
606 if (!(info = mono_thread_info_suspend_sync (id, interrupt_kernel, &suspend_error))) {
607 g_warning ("failed to suspend thread %p due to %s, hopefully it is dead", (gpointer)id, suspend_error);
608 mono_thread_info_suspend_unlock ();
611 /*WARNING: We now are in interrupt context until we resume the thread. */
612 if (!is_thread_in_critical_region (info))
615 if (!mono_thread_info_core_resume (info)) {
616 g_warning ("failed to resume thread %p, hopefully it is dead", (gpointer)id);
617 mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
618 mono_thread_info_suspend_unlock ();
621 THREADS_DEBUG ("restarted thread %p\n", (gpointer)id);
623 if (!sleep_duration) {
631 g_usleep (sleep_duration);
633 sleep_duration += 10;
636 /* XXX this clears HP 1, so we restated it again */
637 mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, TRUE);
638 mono_thread_info_suspend_unlock ();
644 Inject an assynchronous call into the target thread. The target thread must be suspended and
645 only a single async call can be setup for a given suspend cycle.
646 This async call must cause stack unwinding as the current implementation doesn't save enough state
647 to resume execution of the top-of-stack function. It's an acceptable limitation since this is
648 currently used only to deliver exceptions.
651 mono_thread_info_setup_async_call (MonoThreadInfo *info, void (*target_func)(void*), void *user_data)
653 g_assert (info->suspend_count);
654 /*FIXME this is a bad assert, we probably should do proper locking and fail if one is already set*/
655 g_assert (!info->async_target);
656 info->async_target = target_func;
657 /* This is not GC tracked */
658 info->user_data = user_data;
662 The suspend lock is held during any suspend in progress.
663 A GC that has safepoints must take this lock as part of its
664 STW to make sure no unsafe pending suspend is in progress.
667 mono_thread_info_suspend_lock (void)
669 MONO_SEM_WAIT_UNITERRUPTIBLE (&global_suspend_semaphore);
673 mono_thread_info_suspend_unlock (void)
675 MONO_SEM_POST (&global_suspend_semaphore);
679 mono_thread_info_disable_new_interrupt (gboolean disable)
681 disable_new_interrupt = disable;
685 * This is a very specific function whose only purpose is to
686 * break a given thread from socket syscalls.
688 * This only exists because linux won't fail a call to connect
689 * if the underlying is closed.
691 * TODO We should cleanup and unify this with the other syscall abort
695 mono_thread_info_abort_socket_syscall_for_close (MonoNativeThreadId tid)
697 MonoThreadHazardPointers *hp;
698 MonoThreadInfo *info;
700 if (tid == mono_native_thread_id_get () || !mono_threads_core_needs_abort_syscall ())
703 hp = mono_hazard_pointer_get ();
704 info = mono_thread_info_lookup (tid); /*info on HP1*/
708 if (mono_thread_info_run_state (info) > STATE_RUNNING) {
709 mono_hazard_pointer_clear (hp, 1);
713 mono_thread_info_suspend_lock ();
715 mono_threads_core_abort_syscall (info);
717 mono_hazard_pointer_clear (hp, 1);
718 mono_thread_info_suspend_unlock ();
722 Disabled by default for now.
723 To enable this we need mini to implement the callbacks by MonoThreadInfoRuntimeCallbacks
724 which means mono-context and setup_async_callback, and we need a mono-threads backend.
727 mono_thread_info_new_interrupt_enabled (void)
729 /*We need STW gc events to work correctly*/
730 #if defined (HAVE_BOEHM_GC) && !defined (USE_INCLUDED_LIBGC)
734 #if defined(HOST_WIN32)
737 #if defined (__i386__)
738 return !disable_new_interrupt;
744 * mono_thread_info_set_is_async_context:
746 * Set whenever the current thread is in an async context. Some runtime functions might behave
747 * differently while in an async context in order to be async safe.
750 mono_thread_info_set_is_async_context (gboolean async_context)
752 MonoThreadInfo *info = mono_thread_info_current ();
755 info->is_async_context = async_context;
759 mono_thread_info_is_async_context (void)
761 MonoThreadInfo *info = mono_thread_info_current ();
764 return info->is_async_context;
770 * mono_threads_create_thread:
772 * Create a new thread executing START with argument ARG. Store its id into OUT_TID.
773 * Returns: a windows or io-layer handle for the thread.
776 mono_threads_create_thread (LPTHREAD_START_ROUTINE start, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
778 return mono_threads_core_create_thread (start, arg, stack_size, creation_flags, out_tid);
782 * mono_thread_info_get_stack_bounds:
784 * Return the address and size of the current threads stack. Return NULL as the
785 * stack address if the stack address cannot be determined.
788 mono_thread_info_get_stack_bounds (guint8 **staddr, size_t *stsize)
790 mono_threads_core_get_stack_bounds (staddr, stsize);
794 mono_thread_info_yield (void)
796 return mono_threads_core_yield ();
800 mono_thread_info_tls_get (THREAD_INFO_TYPE *info, MonoTlsKey key)
802 return ((MonoThreadInfo*)info)->tls [key];
806 * mono_threads_info_tls_set:
808 * Set the TLS key to VALUE in the info structure. This can be used to obtain
809 * values of TLS variables for threads other than the current thread.
810 * This should only be used for infrequently changing TLS variables, and it should
811 * be paired with setting the real TLS variable since this provides no GC tracking.
814 mono_thread_info_tls_set (THREAD_INFO_TYPE *info, MonoTlsKey key, gpointer value)
816 ((MonoThreadInfo*)info)->tls [key] = value;
820 * mono_thread_info_exit:
822 * Exit the current thread.
823 * This function doesn't return.
826 mono_thread_info_exit (void)
828 mono_threads_core_exit (0);
832 * mono_thread_info_open_handle:
834 * Return a io-layer/win32 handle for the current thread.
835 * The handle need to be closed by calling CloseHandle () when it is no
839 mono_thread_info_open_handle (void)
841 return mono_threads_core_open_handle ();
845 * mono_thread_info_open_handle:
847 * Return a io-layer/win32 handle for the thread identified by HANDLE/TID.
848 * The handle need to be closed by calling CloseHandle () when it is no
852 mono_threads_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
854 return mono_threads_core_open_thread_handle (handle, tid);
858 mono_thread_info_set_name (MonoNativeThreadId tid, const char *name)
860 mono_threads_core_set_name (tid, name);