694d019c22a45b280a8eafbbee03b57cccb6e03b
[mono.git] / mono / utils / mono-threads.c
1 /*
2  * mono-threads.c: Low-level threading
3  *
4  * Author:
5  *      Rodrigo Kumpera (kumpera@gmail.com)
6  *
7  * (C) 2011 Novell, Inc
8  */
9
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/appdomain.h>
16 #include <mono/metadata/domain-internals.h>
17
18 #include <errno.h>
19
20 #define THREADS_DEBUG(...)
21 //#define THREADS_DEBUG(...) g_message(__VA_ARGS__)
22
23 /*
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.
27
28 We could implement this using critical regions, but would be much much
29 harder for an operation that is hardly performance critical.
30
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.
34 */
35 static CRITICAL_SECTION global_suspend_lock;
36
37
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;
43 static gboolean disable_new_interrupt = FALSE;
44
45 static inline void
46 mono_hazard_pointer_clear_all (MonoThreadHazardPointers *hp, int retain)
47 {
48         if (retain != 0)
49                 mono_hazard_pointer_clear (hp, 0);
50         if (retain != 1)
51                 mono_hazard_pointer_clear (hp, 1);
52         if (retain != 2)
53                 mono_hazard_pointer_clear (hp, 2);
54 }
55
56 /*
57 If return non null Hazard Pointer 1 holds the return value.
58 */
59 MonoThreadInfo*
60 mono_thread_info_lookup (MonoNativeThreadId id)
61 {
62                 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
63
64         if (!mono_lls_find (&thread_list, hp, (uintptr_t)id)) {
65                 mono_hazard_pointer_clear_all (hp, -1);
66                 return NULL;
67         } 
68
69         mono_hazard_pointer_clear_all (hp, 1);
70         return mono_hazard_pointer_get_val (hp, 1);
71 }
72
73 static gboolean
74 mono_thread_info_insert (MonoThreadInfo *info)
75 {
76         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
77
78         if (!mono_lls_insert (&thread_list, hp, (MonoLinkedListSetNode*)info)) {
79                 mono_hazard_pointer_clear_all (hp, -1);
80                 return FALSE;
81         } 
82
83         mono_hazard_pointer_clear_all (hp, -1);
84         return TRUE;
85 }
86
87 static gboolean
88 mono_thread_info_remove (MonoThreadInfo *info)
89 {
90         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
91         gboolean res;
92
93         THREADS_DEBUG ("removing info %p\n", info);
94         res = mono_lls_remove (&thread_list, hp, (MonoLinkedListSetNode*)info);
95         mono_hazard_pointer_clear_all (hp, -1);
96         return res;
97 }
98
99 static void
100 free_thread_info (gpointer mem)
101 {
102         MonoThreadInfo *info = mem;
103
104         DeleteCriticalSection (&info->suspend_lock);
105         mono_threads_platform_free (info);
106
107         g_free (info);
108 }
109
110 int
111 mono_thread_info_register_small_id (void)
112 {
113         int small_id = mono_thread_small_id_alloc ();
114         mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (small_id + 1));
115         return small_id;
116 }
117
118 static void*
119 register_thread (MonoThreadInfo *info, gpointer baseptr)
120 {
121         int small_id = mono_thread_info_register_small_id ();
122         gboolean result;
123         mono_thread_info_set_tid (info, mono_native_thread_id_get ());
124         info->small_id = small_id;
125
126         InitializeCriticalSection (&info->suspend_lock);
127
128         /*set TLS early so SMR works */
129         mono_native_tls_set_value (thread_info_key, info);
130
131         THREADS_DEBUG ("registering info %p tid %p small id %x\n", info, mono_thread_info_get_tid (info), info->small_id);
132
133         if (threads_callbacks.thread_register) {
134                 if (threads_callbacks.thread_register (info, baseptr) == NULL) {
135                         g_warning ("thread registation failed\n");
136                         g_free (info);
137                         return NULL;
138                 }
139         }
140
141         mono_threads_platform_register (info);
142
143         /*If this fail it means a given thread has been registered twice, which doesn't make sense. */
144         result = mono_thread_info_insert (info);
145         g_assert (result);
146         return info;
147 }
148
149 static void
150 unregister_thread (void *arg)
151 {
152         MonoThreadInfo *info = arg;
153         int small_id = info->small_id;
154         g_assert (info);
155
156         THREADS_DEBUG ("unregistering info %p\n", info);
157
158         /*
159          * TLS destruction order is not reliable so small_id might be cleaned up
160          * before us.
161          */
162         mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (info->small_id + 1));
163
164         /*
165         The unregister callback is reposible for calling mono_threads_unregister_current_thread
166         since it usually needs to be done in sync with the GC does a stop-the-world.
167         */
168         if (threads_callbacks.thread_unregister)
169                 threads_callbacks.thread_unregister (info);
170         else
171                 mono_threads_unregister_current_thread (info);
172
173         /*now it's safe to free the thread info.*/
174         mono_thread_hazardous_free_or_queue (info, free_thread_info);
175         mono_thread_small_id_free (small_id);
176 }
177
178 /**
179  * Removes the current thread from the thread list.
180  * This must be called from the thread unregister callback and nowhere else.
181  * The current thread must be passed as TLS might have already been cleaned up.
182 */
183 void
184 mono_threads_unregister_current_thread (MonoThreadInfo *info)
185 {
186         gboolean result;
187         g_assert (mono_thread_info_get_tid (info) == mono_native_thread_id_get ());
188         result = mono_thread_info_remove (info);
189         g_assert (result);
190
191 }
192
193 MonoThreadInfo*
194 mono_thread_info_current (void)
195 {
196         return mono_native_tls_get_value (thread_info_key);
197 }
198
199 int
200 mono_thread_info_get_small_id (void)
201 {
202         gpointer val = mono_native_tls_get_value (small_id_key);
203         if (!val)
204                 return -1;
205         return GPOINTER_TO_INT (val) - 1;
206 }
207
208 MonoLinkedListSet*
209 mono_thread_info_list_head (void)
210 {
211         return &thread_list;
212 }
213
214 MonoThreadInfo*
215 mono_thread_info_attach (void *baseptr)
216 {
217         MonoThreadInfo *info = mono_native_tls_get_value (thread_info_key);
218         if (!info) {
219                 info = g_malloc0 (thread_info_size);
220                 THREADS_DEBUG ("attaching %p\n", info);
221                 if (!register_thread (info, baseptr))
222                         return NULL;
223         } else if (threads_callbacks.thread_attach) {
224                 threads_callbacks.thread_attach (info);
225         }
226         return info;
227 }
228
229 void
230 mono_thread_info_dettach (void)
231 {
232         MonoThreadInfo *info = mono_native_tls_get_value (thread_info_key);
233         if (info) {
234                 THREADS_DEBUG ("detaching %p\n", info);
235                 unregister_thread (info);
236         }
237 }
238
239 void
240 mono_threads_init (MonoThreadInfoCallbacks *callbacks, size_t info_size)
241 {
242         gboolean res;
243         threads_callbacks = *callbacks;
244         thread_info_size = info_size;
245 #ifdef HOST_WIN32
246         res = mono_native_tls_alloc (thread_info_key, NULL);
247 #else
248         res = mono_native_tls_alloc (thread_info_key, unregister_thread);
249 #endif
250         g_assert (res);
251
252         res = mono_native_tls_alloc (small_id_key, NULL);
253         g_assert (res);
254
255         InitializeCriticalSection (&global_suspend_lock);
256
257         mono_lls_init (&thread_list, NULL);
258         mono_thread_smr_init ();
259         mono_threads_init_platform ();
260
261         g_assert (sizeof (MonoNativeThreadId) <= sizeof (uintptr_t));
262 }
263
264 void
265 mono_threads_runtime_init (MonoThreadInfoRuntimeCallbacks *callbacks)
266 {
267         runtime_callbacks = *callbacks;
268 }
269
270 MonoThreadInfoCallbacks *
271 mono_threads_get_callbacks (void)
272 {
273         return &threads_callbacks;
274 }
275
276 MonoThreadInfoRuntimeCallbacks *
277 mono_threads_get_runtime_callbacks (void)
278 {
279         return &runtime_callbacks;
280 }
281
282 /*
283 The return value is only valid until a matching mono_thread_info_resume is called
284 */
285 static MonoThreadInfo*
286 mono_thread_info_suspend_sync (MonoNativeThreadId tid, gboolean interrupt_kernel)
287 {
288         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();      
289         MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
290         if (!info)
291                 return NULL;
292
293         EnterCriticalSection (&info->suspend_lock);
294
295         /*thread is on the process of detaching*/
296         if (info->thread_state > STATE_RUNNING) {
297                 mono_hazard_pointer_clear (hp, 1);
298                 return NULL;
299         }
300
301         THREADS_DEBUG ("suspend %x IN COUNT %d\n", tid, info->suspend_count);
302
303         if (info->suspend_count) {
304                 ++info->suspend_count;
305                 mono_hazard_pointer_clear (hp, 1);
306                 LeaveCriticalSection (&info->suspend_lock);
307                 return info;
308         }
309
310         if (!mono_threads_core_suspend (info)) {
311                 LeaveCriticalSection (&info->suspend_lock);
312                 mono_hazard_pointer_clear (hp, 1);
313                 return NULL;
314         }
315
316         if (interrupt_kernel) 
317                 mono_threads_core_interrupt (info);
318
319         ++info->suspend_count;
320         LeaveCriticalSection (&info->suspend_lock);
321         mono_hazard_pointer_clear (hp, 1);
322
323         return info;
324 }
325
326 void
327 mono_thread_info_self_suspend ()
328 {
329         MonoThreadInfo *info = mono_thread_info_current ();
330         if (!info)
331                 return;
332
333         EnterCriticalSection (&info->suspend_lock);
334
335         THREADS_DEBUG ("self suspend IN COUNT %d\n", info->suspend_count);
336
337         g_assert (info->suspend_count == 0);
338         ++info->suspend_count;
339
340         /*
341         The internal API contract with this function is a bit out of the ordinary.
342         mono_threads_core_self_suspend executes with suspend_lock taken and must
343         release it after capturing the current context.
344         */
345         mono_threads_core_self_suspend (info);
346 }
347
348 gboolean
349 mono_thread_info_resume (MonoNativeThreadId tid)
350 {
351         gboolean result = TRUE;
352         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();      
353         MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
354         if (!info)
355                 return FALSE;
356
357         EnterCriticalSection (&info->suspend_lock);
358
359         THREADS_DEBUG ("resume %x IN COUNT %d\n",tid, info->suspend_count);
360
361         if (info->suspend_count <= 0) {
362                 LeaveCriticalSection (&info->suspend_lock);
363                 mono_hazard_pointer_clear (hp, 1);
364                 return FALSE;
365         }
366
367         /*
368          * The theory here is that if we manage to suspend the thread it means it did not
369          * start cleanup since it take the same lock. 
370         */
371         g_assert (mono_thread_info_get_tid (info));
372
373         if (--info->suspend_count == 0)
374                 result = mono_threads_core_resume (info);
375
376         LeaveCriticalSection (&info->suspend_lock);
377         mono_hazard_pointer_clear (hp, 1);
378
379         return result;
380 }
381
382 /*
383 FIXME fix cardtable WB to be out of line and check with the runtime if the target is not the
384 WB trampoline. Another option is to encode wb ranges in MonoJitInfo, but that is somewhat hard.
385 */
386 static gboolean
387 is_thread_in_critical_region (MonoThreadInfo *info)
388 {
389         MonoMethod *method;
390         MonoJitInfo *ji = mono_jit_info_table_find (
391                 info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
392                 MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
393
394         if (!ji)
395                 return FALSE;
396
397         method = ji->method;
398
399         return threads_callbacks.mono_method_is_critical (method);
400 }
401
402 /*
403 WARNING:
404 If we are trying to suspend a target that is on a critical region
405 and running a syscall we risk looping forever if @interrupt_kernel is FALSE.
406 So, be VERY carefull in calling this with @interrupt_kernel == FALSE.
407 */
408 MonoThreadInfo*
409 mono_thread_info_safe_suspend_sync (MonoNativeThreadId id, gboolean interrupt_kernel)
410 {
411         MonoThreadInfo *info = NULL;
412         int sleep_duration = 0;
413
414         /*FIXME: unify this with self-suspend*/
415         g_assert (id != mono_native_thread_id_get ());
416
417         mono_thread_info_suspend_lock ();
418
419         for (;;) {
420                 if (!(info = mono_thread_info_suspend_sync (id, interrupt_kernel))) {
421                         g_warning ("failed to suspend thread %p, hopefully it is dead", (gpointer)id);
422                         mono_thread_info_suspend_unlock ();
423                         return NULL;
424                 }
425                 /*WARNING: We now are in interrupt context until we resume the thread. */
426                 if (!is_thread_in_critical_region (info))
427                         break;
428
429                 if (!mono_thread_info_resume (id)) {
430                         g_warning ("failed to result thread %p, hopefully it is dead", (gpointer)id);
431                         mono_thread_info_suspend_unlock ();
432                         return NULL;
433                 }
434                 THREADS_DEBUG ("restarted thread %p\n", (gpointer)id);
435
436                 if (!sleep_duration) {
437 #ifdef HOST_WIN32
438                         SwitchToThread ();
439 #else
440                         sched_yield ();
441 #endif
442                 }
443                 else {
444                         g_usleep (sleep_duration);
445                 }
446                 sleep_duration += 10;
447         }
448
449         mono_thread_info_suspend_unlock ();
450         return info;
451 }
452
453 /**
454 Inject an assynchronous call into the target thread. The target thread must be suspended and
455 only a single async call can be setup for a given suspend cycle.
456 This async call must cause stack unwinding as the current implementation doesn't save enough state
457 to resume execution of the top-of-stack function. It's an acceptable limitation since this is
458 currently used only to deliver exceptions.
459 */
460 void
461 mono_thread_info_setup_async_call (MonoThreadInfo *info, void (*target_func)(void*), void *user_data)
462 {
463         g_assert (info->suspend_count);
464         /*FIXME this is a bad assert, we probably should do proper locking and fail if one is already set*/
465         g_assert (!info->async_target);
466         info->async_target = target_func;
467         /* This is not GC tracked */
468         info->user_data = user_data;
469 }
470
471 /*
472 The suspend lock is held during any suspend in progress.
473 A GC that has safepoints must take this lock as part of its
474 STW to make sure no unsafe pending suspend is in progress.   
475 */
476 void
477 mono_thread_info_suspend_lock (void)
478 {
479         EnterCriticalSection (&global_suspend_lock);
480 }
481
482 void
483 mono_thread_info_suspend_unlock (void)
484 {
485         LeaveCriticalSection (&global_suspend_lock);
486 }
487
488 void
489 mono_thread_info_disable_new_interrupt (gboolean disable)
490 {
491         disable_new_interrupt = disable;
492 }
493 /*
494 Disabled by default for now.
495 To enable this we need mini to implement the callbacks by MonoThreadInfoRuntimeCallbacks
496 which means mono-context and setup_async_callback, and we need a mono-threads backend.
497 */
498 gboolean
499 mono_thread_info_new_interrupt_enabled (void)
500 {
501         /*We need STW gc events to work correctly*/
502 #if defined (HAVE_BOEHM_GC) && !defined (USE_INCLUDED_LIBGC)
503         return FALSE;
504 #endif
505         /*port not done*/
506 #if defined(HOST_WIN32)
507         return FALSE;
508 #endif
509 #if defined (__i386__)
510         return !disable_new_interrupt;
511 #endif
512         return FALSE;
513 }