/
mono-threads.c
620 lines (516 loc) · 15.9 KB
/
mono-threads.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*
* mono-threads.c: Low-level threading
*
* Author:
* Rodrigo Kumpera (kumpera@gmail.com)
*
* Copyright 2011 Novell, Inc (http://www.novell.com)
* Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
*/
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-semaphore.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-tls.h>
#include <mono/utils/hazard-pointer.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/domain-internals.h>
#include <errno.h>
#if defined(__MACH__)
#include <mono/utils/mach-support.h>
#endif
#define THREADS_DEBUG(...)
//#define THREADS_DEBUG(...) g_message(__VA_ARGS__)
/*
Mutex that makes sure only a single thread can be suspending others.
Suspend is a very racy operation since it requires restarting until
the target thread is not on an unsafe region.
We could implement this using critical regions, but would be much much
harder for an operation that is hardly performance critical.
The GC has to acquire this lock before starting a STW to make sure
a runtime suspend won't make it wronly see a thread in a safepoint
when it is in fact not.
*/
static MonoSemType global_suspend_semaphore;
static int thread_info_size;
static MonoThreadInfoCallbacks threads_callbacks;
static MonoThreadInfoRuntimeCallbacks runtime_callbacks;
static MonoNativeTlsKey thread_info_key, small_id_key;
static MonoLinkedListSet thread_list;
static gboolean disable_new_interrupt = FALSE;
static gboolean mono_threads_inited = FALSE;
static inline void
mono_hazard_pointer_clear_all (MonoThreadHazardPointers *hp, int retain)
{
if (retain != 0)
mono_hazard_pointer_clear (hp, 0);
if (retain != 1)
mono_hazard_pointer_clear (hp, 1);
if (retain != 2)
mono_hazard_pointer_clear (hp, 2);
}
/*
If return non null Hazard Pointer 1 holds the return value.
*/
MonoThreadInfo*
mono_thread_info_lookup (MonoNativeThreadId id)
{
MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
if (!mono_lls_find (&thread_list, hp, (uintptr_t)id)) {
mono_hazard_pointer_clear_all (hp, -1);
return NULL;
}
mono_hazard_pointer_clear_all (hp, 1);
return mono_hazard_pointer_get_val (hp, 1);
}
static gboolean
mono_thread_info_insert (MonoThreadInfo *info)
{
MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
if (!mono_lls_insert (&thread_list, hp, (MonoLinkedListSetNode*)info)) {
mono_hazard_pointer_clear_all (hp, -1);
return FALSE;
}
mono_hazard_pointer_clear_all (hp, -1);
return TRUE;
}
static gboolean
mono_thread_info_remove (MonoThreadInfo *info)
{
MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
gboolean res;
THREADS_DEBUG ("removing info %p\n", info);
res = mono_lls_remove (&thread_list, hp, (MonoLinkedListSetNode*)info);
mono_hazard_pointer_clear_all (hp, -1);
return res;
}
static void
free_thread_info (gpointer mem)
{
MonoThreadInfo *info = mem;
MONO_SEM_DESTROY (&info->suspend_semaphore);
MONO_SEM_DESTROY (&info->resume_semaphore);
MONO_SEM_DESTROY (&info->finish_resume_semaphore);
mono_threads_platform_free (info);
g_free (info);
}
int
mono_thread_info_register_small_id (void)
{
int small_id = mono_thread_small_id_alloc ();
mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (small_id + 1));
return small_id;
}
static void*
register_thread (MonoThreadInfo *info, gpointer baseptr)
{
int small_id = mono_thread_info_register_small_id ();
gboolean result;
mono_thread_info_set_tid (info, mono_native_thread_id_get ());
info->small_id = small_id;
MONO_SEM_INIT (&info->suspend_semaphore, 1);
MONO_SEM_INIT (&info->resume_semaphore, 0);
MONO_SEM_INIT (&info->finish_resume_semaphore, 0);
/*set TLS early so SMR works */
mono_native_tls_set_value (thread_info_key, info);
THREADS_DEBUG ("registering info %p tid %p small id %x\n", info, mono_thread_info_get_tid (info), info->small_id);
if (threads_callbacks.thread_register) {
if (threads_callbacks.thread_register (info, baseptr) == NULL) {
g_warning ("thread registation failed\n");
g_free (info);
return NULL;
}
}
mono_threads_platform_register (info);
/*If this fail it means a given thread has been registered twice, which doesn't make sense. */
result = mono_thread_info_insert (info);
g_assert (result);
return info;
}
static void
unregister_thread (void *arg)
{
MonoThreadInfo *info = arg;
int small_id = info->small_id;
g_assert (info);
THREADS_DEBUG ("unregistering info %p\n", info);
/*
* TLS destruction order is not reliable so small_id might be cleaned up
* before us.
*/
mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (info->small_id + 1));
/*
The unregister callback is reposible for calling mono_threads_unregister_current_thread
since it usually needs to be done in sync with the GC does a stop-the-world.
*/
if (threads_callbacks.thread_unregister)
threads_callbacks.thread_unregister (info);
else
mono_threads_unregister_current_thread (info);
/*now it's safe to free the thread info.*/
mono_thread_hazardous_free_or_queue (info, free_thread_info, TRUE, FALSE);
mono_thread_small_id_free (small_id);
}
/**
* Removes the current thread from the thread list.
* This must be called from the thread unregister callback and nowhere else.
* The current thread must be passed as TLS might have already been cleaned up.
*/
void
mono_threads_unregister_current_thread (MonoThreadInfo *info)
{
gboolean result;
g_assert (mono_thread_info_get_tid (info) == mono_native_thread_id_get ());
result = mono_thread_info_remove (info);
g_assert (result);
}
MonoThreadInfo*
mono_thread_info_current (void)
{
return mono_native_tls_get_value (thread_info_key);
}
int
mono_thread_info_get_small_id (void)
{
gpointer val = mono_native_tls_get_value (small_id_key);
if (!val)
return -1;
return GPOINTER_TO_INT (val) - 1;
}
MonoLinkedListSet*
mono_thread_info_list_head (void)
{
return &thread_list;
}
MonoThreadInfo*
mono_thread_info_attach (void *baseptr)
{
MonoThreadInfo *info;
if (!mono_threads_inited)
{
/* This can happen from DllMain(DLL_THREAD_ATTACH) on Windows, if a
* thread is created before an embedding API user initialized Mono. */
THREADS_DEBUG ("mono_thread_info_attach called before mono_threads_init\n");
return NULL;
}
info = mono_native_tls_get_value (thread_info_key);
if (!info) {
info = g_malloc0 (thread_info_size);
THREADS_DEBUG ("attaching %p\n", info);
if (!register_thread (info, baseptr))
return NULL;
} else if (threads_callbacks.thread_attach) {
threads_callbacks.thread_attach (info);
}
return info;
}
void
mono_thread_info_dettach (void)
{
MonoThreadInfo *info;
if (!mono_threads_inited)
{
/* This can happen from DllMain(THREAD_DETACH) on Windows, if a thread
* is created before an embedding API user initialized Mono. */
THREADS_DEBUG ("mono_thread_info_dettach called before mono_threads_init\n");
return;
}
info = mono_native_tls_get_value (thread_info_key);
if (info) {
THREADS_DEBUG ("detaching %p\n", info);
unregister_thread (info);
mono_native_tls_set_value (thread_info_key, NULL);
}
}
void
mono_threads_init (MonoThreadInfoCallbacks *callbacks, size_t info_size)
{
gboolean res;
threads_callbacks = *callbacks;
thread_info_size = info_size;
#ifdef HOST_WIN32
res = mono_native_tls_alloc (&thread_info_key, NULL);
#else
res = mono_native_tls_alloc (&thread_info_key, unregister_thread);
#endif
g_assert (res);
res = mono_native_tls_alloc (&small_id_key, NULL);
g_assert (res);
MONO_SEM_INIT (&global_suspend_semaphore, 1);
mono_lls_init (&thread_list, NULL);
mono_thread_smr_init ();
mono_threads_init_platform ();
#if defined(__MACH__)
mono_mach_init (thread_info_key);
#endif
mono_threads_inited = TRUE;
g_assert (sizeof (MonoNativeThreadId) <= sizeof (uintptr_t));
}
void
mono_threads_runtime_init (MonoThreadInfoRuntimeCallbacks *callbacks)
{
runtime_callbacks = *callbacks;
}
MonoThreadInfoCallbacks *
mono_threads_get_callbacks (void)
{
return &threads_callbacks;
}
MonoThreadInfoRuntimeCallbacks *
mono_threads_get_runtime_callbacks (void)
{
return &runtime_callbacks;
}
/*
The return value is only valid until a matching mono_thread_info_resume is called
*/
static MonoThreadInfo*
mono_thread_info_suspend_sync (MonoNativeThreadId tid, gboolean interrupt_kernel)
{
MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
if (!info)
return NULL;
MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
/*thread is on the process of detaching*/
if (mono_thread_info_run_state (info) > STATE_RUNNING) {
mono_hazard_pointer_clear (hp, 1);
return NULL;
}
THREADS_DEBUG ("suspend %x IN COUNT %d\n", tid, info->suspend_count);
if (info->suspend_count) {
++info->suspend_count;
mono_hazard_pointer_clear (hp, 1);
MONO_SEM_POST (&info->suspend_semaphore);
return info;
}
if (!mono_threads_core_suspend (info)) {
MONO_SEM_POST (&info->suspend_semaphore);
mono_hazard_pointer_clear (hp, 1);
return NULL;
}
if (interrupt_kernel)
mono_threads_core_interrupt (info);
++info->suspend_count;
info->thread_state |= STATE_SUSPENDED;
MONO_SEM_POST (&info->suspend_semaphore);
mono_hazard_pointer_clear (hp, 1);
return info;
}
void
mono_thread_info_self_suspend (void)
{
gboolean ret;
MonoThreadInfo *info = mono_thread_info_current ();
if (!info)
return;
MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
THREADS_DEBUG ("self suspend IN COUNT %d\n", info->suspend_count);
g_assert (info->suspend_count == 0);
++info->suspend_count;
info->thread_state |= STATE_SELF_SUSPENDED;
ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&info->suspend_state, NULL);
g_assert (ret);
MONO_SEM_POST (&info->suspend_semaphore);
MONO_SEM_WAIT_UNITERRUPTIBLE (&info->resume_semaphore);
g_assert (!info->async_target); /*FIXME this should happen normally for suspend. */
MONO_SEM_POST (&info->finish_resume_semaphore);
}
static gboolean
mono_thread_info_resume_internal (MonoThreadInfo *info)
{
gboolean result;
if (mono_thread_info_suspend_state (info) == STATE_SELF_SUSPENDED) {
MONO_SEM_POST (&info->resume_semaphore);
MONO_SEM_WAIT_UNITERRUPTIBLE (&info->finish_resume_semaphore);
result = TRUE;
} else {
result = mono_threads_core_resume (info);
}
info->thread_state &= ~SUSPEND_STATE_MASK;
return result;
}
gboolean
mono_thread_info_resume (MonoNativeThreadId tid)
{
gboolean result = TRUE;
MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
if (!info)
return FALSE;
MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
THREADS_DEBUG ("resume %x IN COUNT %d\n",tid, info->suspend_count);
if (info->suspend_count <= 0) {
MONO_SEM_POST (&info->suspend_semaphore);
mono_hazard_pointer_clear (hp, 1);
return FALSE;
}
/*
* The theory here is that if we manage to suspend the thread it means it did not
* start cleanup since it take the same lock.
*/
g_assert (mono_thread_info_get_tid (info));
if (--info->suspend_count == 0)
result = mono_thread_info_resume_internal (info);
MONO_SEM_POST (&info->suspend_semaphore);
mono_hazard_pointer_clear (hp, 1);
mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, FALSE);
return result;
}
void
mono_thread_info_finish_suspend (void)
{
mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, FALSE);
}
/*
FIXME fix cardtable WB to be out of line and check with the runtime if the target is not the
WB trampoline. Another option is to encode wb ranges in MonoJitInfo, but that is somewhat hard.
*/
static gboolean
is_thread_in_critical_region (MonoThreadInfo *info)
{
MonoMethod *method;
MonoJitInfo *ji;
if (info->inside_critical_region)
return TRUE;
ji = mono_jit_info_table_find (
info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
if (!ji)
return FALSE;
method = ji->method;
return threads_callbacks.mono_method_is_critical (method);
}
/*
WARNING:
If we are trying to suspend a target that is on a critical region
and running a syscall we risk looping forever if @interrupt_kernel is FALSE.
So, be VERY carefull in calling this with @interrupt_kernel == FALSE.
*/
MonoThreadInfo*
mono_thread_info_safe_suspend_sync (MonoNativeThreadId id, gboolean interrupt_kernel)
{
MonoThreadInfo *info = NULL;
int sleep_duration = 0;
/*FIXME: unify this with self-suspend*/
g_assert (id != mono_native_thread_id_get ());
mono_thread_info_suspend_lock ();
for (;;) {
if (!(info = mono_thread_info_suspend_sync (id, interrupt_kernel))) {
g_warning ("failed to suspend thread %p, hopefully it is dead", (gpointer)id);
mono_thread_info_suspend_unlock ();
return NULL;
}
/*WARNING: We now are in interrupt context until we resume the thread. */
if (!is_thread_in_critical_region (info))
break;
if (!mono_thread_info_resume (id)) {
g_warning ("failed to result thread %p, hopefully it is dead", (gpointer)id);
mono_thread_info_suspend_unlock ();
return NULL;
}
THREADS_DEBUG ("restarted thread %p\n", (gpointer)id);
if (!sleep_duration) {
#ifdef HOST_WIN32
SwitchToThread ();
#else
sched_yield ();
#endif
}
else {
g_usleep (sleep_duration);
}
sleep_duration += 10;
}
mono_atomic_store_release (&mono_thread_info_current ()->inside_critical_region, TRUE);
mono_thread_info_suspend_unlock ();
return info;
}
/**
Inject an assynchronous call into the target thread. The target thread must be suspended and
only a single async call can be setup for a given suspend cycle.
This async call must cause stack unwinding as the current implementation doesn't save enough state
to resume execution of the top-of-stack function. It's an acceptable limitation since this is
currently used only to deliver exceptions.
*/
void
mono_thread_info_setup_async_call (MonoThreadInfo *info, void (*target_func)(void*), void *user_data)
{
g_assert (info->suspend_count);
/*FIXME this is a bad assert, we probably should do proper locking and fail if one is already set*/
g_assert (!info->async_target);
info->async_target = target_func;
/* This is not GC tracked */
info->user_data = user_data;
}
/*
The suspend lock is held during any suspend in progress.
A GC that has safepoints must take this lock as part of its
STW to make sure no unsafe pending suspend is in progress.
*/
void
mono_thread_info_suspend_lock (void)
{
MONO_SEM_WAIT_UNITERRUPTIBLE (&global_suspend_semaphore);
}
void
mono_thread_info_suspend_unlock (void)
{
MONO_SEM_POST (&global_suspend_semaphore);
}
void
mono_thread_info_disable_new_interrupt (gboolean disable)
{
disable_new_interrupt = disable;
}
/*
* This is a very specific function whose only purpose is to
* break a given thread from socket syscalls.
*
* This only exists because linux won't fail a call to connect
* if the underlying is closed.
*
* TODO We should cleanup and unify this with the other syscall abort
* facility.
*/
void
mono_thread_info_abort_socket_syscall_for_close (MonoNativeThreadId tid)
{
MonoThreadHazardPointers *hp;
MonoThreadInfo *info;
if (tid == mono_native_thread_id_get () || !mono_threads_core_needs_abort_syscall ())
return;
hp = mono_hazard_pointer_get ();
info = mono_thread_info_lookup (tid); /*info on HP1*/
if (!info)
return;
if (mono_thread_info_run_state (info) > STATE_RUNNING) {
mono_hazard_pointer_clear (hp, 1);
return;
}
mono_thread_info_suspend_lock ();
mono_threads_core_abort_syscall (info);
mono_hazard_pointer_clear (hp, 1);
mono_thread_info_suspend_unlock ();
}
/*
Disabled by default for now.
To enable this we need mini to implement the callbacks by MonoThreadInfoRuntimeCallbacks
which means mono-context and setup_async_callback, and we need a mono-threads backend.
*/
gboolean
mono_thread_info_new_interrupt_enabled (void)
{
/*We need STW gc events to work correctly*/
#if defined (HAVE_BOEHM_GC) && !defined (USE_INCLUDED_LIBGC)
return FALSE;
#endif
/*port not done*/
#if defined(HOST_WIN32)
return FALSE;
#endif
#if defined (__i386__)
return !disable_new_interrupt;
#endif
return FALSE;
}