2 * mono-threads.c: Low-level threading
5 * Rodrigo Kumpera (kumpera@gmail.com)
10 #include <mono/utils/mono-compiler.h>
11 #include <mono/utils/mono-semaphore.h>
12 #include <mono/utils/mono-threads.h>
13 #include <mono/utils/mono-tls.h>
14 #include <mono/utils/hazard-pointer.h>
15 #include <mono/metadata/gc-internal.h>
16 #include <mono/metadata/appdomain.h>
20 #define THREADS_DEBUG(...)
21 //#define THREADS_DEBUG(...) g_message(__VA_ARGS__)
24 Mutex that makes sure only a single thread can be suspending others.
25 Suspend is a very racy operation since it requires restarting until
26 the target thread is not on an unsafe region.
28 We could implement this using critical regions, but would be much much
29 harder for an operation that is hardly performance critical.
31 The GC has to acquire this lock before starting a STW to make sure
32 a runtime suspend won't make it wronly see a thread in a safepoint
33 when it is in fact not.
35 static CRITICAL_SECTION global_suspend_lock;
38 static int thread_info_size;
39 static MonoThreadInfoCallbacks threads_callbacks;
40 static MonoThreadInfoRuntimeCallbacks runtime_callbacks;
41 static MonoNativeTlsKey thread_info_key, small_id_key;
42 static MonoLinkedListSet thread_list;
45 mono_hazard_pointer_clear_all (MonoThreadHazardPointers *hp, int retain)
48 mono_hazard_pointer_clear (hp, 0);
50 mono_hazard_pointer_clear (hp, 1);
52 mono_hazard_pointer_clear (hp, 2);
56 If return non null Hazard Pointer 1 holds the return value.
59 mono_thread_info_lookup (MonoNativeThreadId id)
61 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
63 if (!mono_lls_find (&thread_list, hp, (uintptr_t)id)) {
64 mono_hazard_pointer_clear_all (hp, -1);
68 mono_hazard_pointer_clear_all (hp, 1);
69 return mono_hazard_pointer_get_val (hp, 1);
73 mono_thread_info_insert (MonoThreadInfo *info)
75 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
77 if (!mono_lls_insert (&thread_list, hp, (MonoLinkedListSetNode*)info)) {
78 mono_hazard_pointer_clear_all (hp, -1);
82 mono_hazard_pointer_clear_all (hp, -1);
87 mono_thread_info_remove (MonoThreadInfo *info)
89 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
92 THREADS_DEBUG ("removing info %p\n", info);
93 res = mono_lls_remove (&thread_list, hp, (MonoLinkedListSetNode*)info);
94 mono_hazard_pointer_clear_all (hp, -1);
99 free_thread_info (gpointer mem)
101 MonoThreadInfo *info = mem;
103 DeleteCriticalSection (&info->suspend_lock);
104 mono_threads_platform_free (info);
110 register_thread (MonoThreadInfo *info, gpointer baseptr)
113 mono_thread_info_set_tid (info, mono_native_thread_id_get ());
114 info->small_id = mono_thread_small_id_alloc ();
116 InitializeCriticalSection (&info->suspend_lock);
118 /*set TLS early so SMR works */
119 mono_native_tls_set_value (thread_info_key, info);
120 mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (info->small_id + 1));
122 THREADS_DEBUG ("registering info %p tid %p small id %x\n", info, mono_thread_info_get_tid (info), info->small_id);
124 if (threads_callbacks.thread_register) {
125 if (threads_callbacks.thread_register (info, baseptr) == NULL) {
126 g_warning ("thread registation failed\n");
132 mono_threads_platform_register (info);
134 /*If this fail it means a given thread has been registered twice, which doesn't make sense. */
135 result = mono_thread_info_insert (info);
141 unregister_thread (void *arg)
143 MonoThreadInfo *info = arg;
144 int small_id = info->small_id;
147 THREADS_DEBUG ("unregistering info %p\n", info);
150 * TLS destruction order is not reliable so small_id might be cleaned up
153 mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (info->small_id + 1));
156 The unregister callback is reposible for calling mono_threads_unregister_current_thread
157 since it usually needs to be done in sync with the GC does a stop-the-world.
159 if (threads_callbacks.thread_unregister)
160 threads_callbacks.thread_unregister (info);
162 mono_threads_unregister_current_thread (info);
164 /*now it's safe to free the thread info.*/
165 mono_thread_hazardous_free_or_queue (info, free_thread_info);
166 mono_thread_small_id_free (small_id);
170 * Removes the current thread from the thread list.
171 * This must be called from the thread unregister callback and nowhere else.
172 * The current thread must be passed as TLS might have already been cleaned up.
175 mono_threads_unregister_current_thread (MonoThreadInfo *info)
178 g_assert (mono_thread_info_get_tid (info) == mono_native_thread_id_get ());
179 result = mono_thread_info_remove (info);
185 mono_thread_info_current (void)
187 return mono_native_tls_get_value (thread_info_key);
191 mono_thread_info_get_small_id (void)
193 gpointer val = mono_native_tls_get_value (small_id_key);
196 return GPOINTER_TO_INT (val) - 1;
200 mono_thread_info_list_head (void)
206 mono_thread_info_attach (void *baseptr)
208 MonoThreadInfo *info = mono_native_tls_get_value (thread_info_key);
210 info = g_malloc0 (thread_info_size);
211 THREADS_DEBUG ("attaching %p\n", info);
212 if (!register_thread (info, baseptr))
214 } else if (threads_callbacks.thread_attach) {
215 threads_callbacks.thread_attach (info);
221 mono_thread_info_dettach (void)
223 MonoThreadInfo *info = mono_native_tls_get_value (thread_info_key);
225 THREADS_DEBUG ("detaching %p\n", info);
226 unregister_thread (info);
231 mono_threads_init (MonoThreadInfoCallbacks *callbacks, size_t info_size)
234 threads_callbacks = *callbacks;
235 thread_info_size = info_size;
237 res = mono_native_tls_alloc (thread_info_key, NULL);
239 res = mono_native_tls_alloc (thread_info_key, unregister_thread);
243 res = mono_native_tls_alloc (small_id_key, NULL);
246 InitializeCriticalSection (&global_suspend_lock);
248 mono_lls_init (&thread_list, NULL);
249 mono_thread_smr_init ();
250 mono_threads_init_platform ();
252 g_assert (sizeof (MonoNativeThreadId) <= sizeof (uintptr_t));
256 mono_threads_runtime_init (MonoThreadInfoRuntimeCallbacks *callbacks)
258 runtime_callbacks = *callbacks;
261 MonoThreadInfoRuntimeCallbacks *
262 mono_threads_get_runtime_callbacks (void)
264 return &runtime_callbacks;
268 The return value is only valid until a matching mono_thread_info_resume is called
270 static MonoThreadInfo*
271 mono_thread_info_suspend_sync (MonoNativeThreadId tid, gboolean interrupt_kernel)
273 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
274 MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
278 EnterCriticalSection (&info->suspend_lock);
280 /*thread is on the process of detaching*/
281 if (info->thread_state > STATE_RUNNING) {
282 mono_hazard_pointer_clear (hp, 1);
286 THREADS_DEBUG ("suspend %x IN COUNT %d\n", tid, info->suspend_count);
288 if (info->suspend_count) {
289 ++info->suspend_count;
290 mono_hazard_pointer_clear (hp, 1);
291 LeaveCriticalSection (&info->suspend_lock);
295 if (!mono_threads_core_suspend (info)) {
296 LeaveCriticalSection (&info->suspend_lock);
297 mono_hazard_pointer_clear (hp, 1);
301 if (interrupt_kernel)
302 mono_threads_core_interrupt (info);
304 ++info->suspend_count;
305 LeaveCriticalSection (&info->suspend_lock);
306 mono_hazard_pointer_clear (hp, 1);
312 mono_thread_info_self_suspend ()
314 MonoThreadInfo *info = mono_thread_info_current ();
318 EnterCriticalSection (&info->suspend_lock);
320 THREADS_DEBUG ("self suspend IN COUNT %d\n", info->suspend_count);
322 g_assert (info->suspend_count == 0);
323 ++info->suspend_count;
326 The internal API contract with this function is a bit out of the ordinary.
327 mono_threads_core_self_suspend executes with suspend_lock taken and must
328 release it after capturing the current context.
330 mono_threads_core_self_suspend (info);
334 mono_thread_info_resume (MonoNativeThreadId tid)
336 gboolean result = TRUE;
337 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
338 MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
342 EnterCriticalSection (&info->suspend_lock);
344 THREADS_DEBUG ("resume %x IN COUNT %d\n",tid, info->suspend_count);
346 if (info->suspend_count <= 0) {
347 LeaveCriticalSection (&info->suspend_lock);
348 mono_hazard_pointer_clear (hp, 1);
353 * The theory here is that if we manage to suspend the thread it means it did not
354 * start cleanup since it take the same lock.
356 g_assert (mono_thread_info_get_tid (info));
358 if (--info->suspend_count == 0)
359 result = mono_threads_core_resume (info);
361 LeaveCriticalSection (&info->suspend_lock);
362 mono_hazard_pointer_clear (hp, 1);
368 FIXME fix cardtable WB to be out of line and check with the runtime if the target is not the
369 WB trampoline. Another option is to encode wb ranges in MonoJitInfo, but that is somewhat hard.
372 is_thread_in_critical_region (MonoThreadInfo *info)
375 MonoJitInfo *ji = mono_jit_info_table_find (
376 info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
377 MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
384 return mono_gc_is_critical_method (method);
389 If we are trying to suspend a target that is on a critical region
390 and running a syscall we risk looping forever if @interrupt_kernel is FALSE.
391 So, be VERY carefull in calling this with @interrupt_kernel == FALSE.
394 mono_thread_info_safe_suspend_sync (MonoNativeThreadId id, gboolean interrupt_kernel)
396 MonoThreadInfo *info = NULL;
397 int sleep_duration = 0;
399 /*FIXME: unify this with self-suspend*/
400 g_assert (id != mono_native_thread_id_get ());
402 mono_thread_info_suspend_lock ();
405 if (!(info = mono_thread_info_suspend_sync (id, interrupt_kernel))) {
406 g_warning ("failed to suspend thread %p, hopefully it is dead", (gpointer)id);
407 mono_thread_info_suspend_unlock ();
410 /*WARNING: We now are in interrupt context until we resume the thread. */
411 if (!is_thread_in_critical_region (info))
414 if (!mono_thread_info_resume (id)) {
415 g_warning ("failed to result thread %p, hopefully it is dead", (gpointer)id);
416 mono_thread_info_suspend_unlock ();
419 THREADS_DEBUG ("restarted thread %p\n", (gpointer)id);
421 if (!sleep_duration) {
429 g_usleep (sleep_duration);
431 sleep_duration += 10;
434 mono_thread_info_suspend_unlock ();
439 Inject an assynchronous call into the target thread. The target thread must be suspended and
440 only a single async call can be setup for a given suspend cycle.
441 This async call must cause stack unwinding as the current implementation doesn't save enough state
442 to resume execution of the top-of-stack function. It's an acceptable limitation since this is
443 currently used only to deliver exceptions.
446 mono_thread_info_setup_async_call (MonoThreadInfo *info, void (*target_func)(void*), void *user_data)
448 g_assert (info->suspend_count);
449 /*FIXME this is a bad assert, we probably should do proper locking and fail if one is already set*/
450 g_assert (!info->async_target);
451 info->async_target = target_func;
452 /* This is not GC tracked */
453 info->user_data = user_data;
457 The suspend lock is held during any suspend in progress.
458 A GC that has safepoints must take this lock as part of its
459 STW to make sure no unsafe pending suspend is in progress.
462 mono_thread_info_suspend_lock (void)
464 EnterCriticalSection (&global_suspend_lock);
468 mono_thread_info_suspend_unlock (void)
470 LeaveCriticalSection (&global_suspend_lock);
474 Disabled by default for now.
475 To enable this we need mini to implement the callbacks by MonoThreadInfoRuntimeCallbacks
476 which means mono-context and setup_async_callback, and we need a mono-threads backend.
479 mono_thread_info_new_interrupt_enabled (void)