Merge pull request #3973 from mono/small-perf
[mono.git] / mono / utils / mono-threads.h
1 /*
2  * mono-threads.h: Low-level threading
3  *
4  * Author:
5  *      Rodrigo Kumpera (kumpera@gmail.com)
6  *
7  * (C) 2011 Novell, Inc
8  */
9
10 #ifndef __MONO_THREADS_H__
11 #define __MONO_THREADS_H__
12
13 #include <mono/utils/mono-os-semaphore.h>
14 #include <mono/utils/mono-stack-unwinding.h>
15 #include <mono/utils/mono-linked-list-set.h>
16 #include <mono/utils/mono-tls.h>
17 #include <mono/utils/mono-coop-semaphore.h>
18 #include <mono/utils/os-event.h>
19 #include <mono/utils/refcount.h>
20
21 #include <mono/io-layer/io-layer.h>
22
23 #include <glib.h>
24 #include <config.h>
25 #ifdef HOST_WIN32
26
27 #include <windows.h>
28
29 typedef DWORD MonoNativeThreadId;
30 typedef HANDLE MonoNativeThreadHandle; /* unused */
31
32 typedef DWORD mono_native_thread_return_t;
33 typedef DWORD mono_thread_start_return_t;
34
35 #define MONO_NATIVE_THREAD_ID_TO_UINT(tid) (tid)
36 #define MONO_UINT_TO_NATIVE_THREAD_ID(tid) ((MonoNativeThreadId)(tid))
37
38 typedef LPTHREAD_START_ROUTINE MonoThreadStart;
39
40 #else
41
42 #include <pthread.h>
43
44 #if defined(__MACH__)
45 #include <mono/utils/mach-support.h>
46
47 typedef thread_port_t MonoNativeThreadHandle;
48
49 #else
50
51 #include <unistd.h>
52
53 typedef pid_t MonoNativeThreadHandle;
54
55 #endif /* defined(__MACH__) */
56
57 typedef pthread_t MonoNativeThreadId;
58
59 typedef void* mono_native_thread_return_t;
60 typedef gsize mono_thread_start_return_t;
61
62 #define MONO_NATIVE_THREAD_ID_TO_UINT(tid) (gsize)(tid)
63 #define MONO_UINT_TO_NATIVE_THREAD_ID(tid) (MonoNativeThreadId)(gsize)(tid)
64
65 typedef gsize (*MonoThreadStart)(gpointer);
66
67 #endif /* #ifdef HOST_WIN32 */
68
69 typedef struct {
70         MonoRefCount ref;
71         MonoOSEvent event;
72 } MonoThreadHandle;
73
74 /*
75 THREAD_INFO_TYPE is a way to make the mono-threads module parametric - or sort of.
76 The GC using mono-threads might extend the MonoThreadInfo struct to add its own
77 data, this avoid a pointer indirection on what is on a lot of hot paths.
78
79 But extending MonoThreadInfo has de disavantage that all functions here return type
80 would require a cast, something like the following:
81
82 typedef struct {
83         MonoThreadInfo info;
84         int stuff;
85 }  MyThreadInfo;
86
87 ...
88 ((MyThreadInfo*)mono_thread_info_current ())->stuff = 1;
89
90 While porting sgen to use mono-threads, the number of casts required was too much and
91 code ended up looking horrible. So we use this cute little hack. The idea is that
92 whomever is including this header can set the expected type to be used by functions here
93 and reduce the number of casts drastically.
94
95 */
96 #ifndef THREAD_INFO_TYPE
97 #define THREAD_INFO_TYPE MonoThreadInfo
98 #endif
99
100 /* Mono Threads internal configuration knows*/
101
102 /* If this is defined, use the signals backed on Mach. Debug only as signals can't be made usable on OSX. */
103 // #define USE_SIGNALS_ON_MACH
104
105 #if defined (_POSIX_VERSION) || defined (__native_client__)
106 #if defined (__MACH__) && !defined (USE_SIGNALS_ON_MACH)
107 #define USE_MACH_BACKEND
108 #else
109 #define USE_POSIX_BACKEND
110 #endif
111 #elif HOST_WIN32
112 #define USE_WINDOWS_BACKEND
113 #else
114 #error "no backend support for current platform"
115 #endif /* defined (_POSIX_VERSION) || defined (__native_client__) */
116
117 enum {
118         STATE_STARTING                          = 0x00,
119         STATE_RUNNING                           = 0x01,
120         STATE_DETACHED                          = 0x02,
121
122         STATE_ASYNC_SUSPENDED                   = 0x03,
123         STATE_SELF_SUSPENDED                    = 0x04,
124         STATE_ASYNC_SUSPEND_REQUESTED   = 0x05,
125         STATE_SELF_SUSPEND_REQUESTED    = 0x06,
126         STATE_BLOCKING                                  = 0x07,
127         STATE_BLOCKING_AND_SUSPENDED    = 0x8,
128
129         STATE_MAX                                               = 0x08,
130
131         THREAD_STATE_MASK                       = 0x00FF,
132         THREAD_SUSPEND_COUNT_MASK       = 0xFF00,
133         THREAD_SUSPEND_COUNT_SHIFT      = 8,
134         THREAD_SUSPEND_COUNT_MAX        = 0xFF,
135
136         SELF_SUSPEND_STATE_INDEX = 0,
137         ASYNC_SUSPEND_STATE_INDEX = 1,
138 };
139
140 typedef struct _MonoThreadInfoInterruptToken MonoThreadInfoInterruptToken;
141
142 typedef struct {
143         MonoLinkedListSetNode node;
144         guint32 small_id; /*Used by hazard pointers */
145         MonoNativeThreadHandle native_handle; /* Valid on mach and android */
146         int thread_state;
147
148         /*Tells if this thread was created by the runtime or not.*/
149         gboolean runtime_thread;
150
151         /* Tells if this thread should be ignored or not by runtime services such as GC and profiling */
152         gboolean tools_thread;
153
154         /* Max stack bounds, all valid addresses must be between [stack_start_limit, stack_end[ */
155         void *stack_start_limit, *stack_end;
156
157         /* suspend machinery, fields protected by suspend_semaphore */
158         MonoSemType suspend_semaphore;
159         int suspend_count;
160
161         MonoSemType resume_semaphore;
162
163         /* only needed by the posix backend */
164 #if defined(USE_POSIX_BACKEND)
165         MonoSemType finish_resume_semaphore;
166         gboolean syscall_break_signal;
167         int signal;
168 #endif
169
170         gboolean suspend_can_continue;
171
172         /* This memory pool is used by coop GC to save stack data roots between GC unsafe regions */
173         GByteArray *stackdata;
174
175         /*In theory, only the posix backend needs this, but having it on mach/win32 simplifies things a lot.*/
176         MonoThreadUnwindState thread_saved_state [2]; //0 is self suspend, 1 is async suspend.
177
178         /*async call machinery, thread MUST be suspended before accessing those fields*/
179         void (*async_target)(void*);
180         void *user_data;
181
182         /*
183         If true, this thread is running a critical region of code and cannot be suspended.
184         A critical session is implicitly started when you call mono_thread_info_safe_suspend_sync
185         and is ended when you call either mono_thread_info_resume or mono_thread_info_finish_suspend.
186         */
187         gboolean inside_critical_region;
188
189         /*
190          * If TRUE, the thread is in async context. Code can use this information to avoid async-unsafe
191          * operations like locking without having to pass an 'async' parameter around.
192          */
193         gboolean is_async_context;
194
195         /*
196          * Values of TLS variables for this thread.
197          * This can be used to obtain the values of TLS variable for threads
198          * other than the current one.
199          */
200         gpointer tls [TLS_KEY_NUM];
201
202         /* IO layer handle for this thread */
203         /* Set when the thread is started, or in _wapi_thread_duplicate () */
204         MonoThreadHandle *handle;
205
206         void *jit_data;
207
208         MonoThreadInfoInterruptToken *interrupt_token;
209
210         /* HandleStack for coop handles */
211         gpointer handle_stack;
212
213         /* Stack mark for targets that explicitly require one */
214         gpointer stack_mark;
215 } MonoThreadInfo;
216
217 typedef struct {
218         void* (*thread_register)(THREAD_INFO_TYPE *info, void *baseaddr);
219         /*
220         This callback is called with @info still on the thread list.
221         This call is made while holding the suspend lock, so don't do callbacks.
222         SMR remains functional as its small_id has not been reclaimed.
223         */
224         void (*thread_unregister)(THREAD_INFO_TYPE *info);
225         /*
226         This callback is called right before thread_unregister. This is called
227         without any locks held so it's the place for complicated cleanup.
228
229         The thread must remain operational between this call and thread_unregister.
230         It must be possible to successfully suspend it after thread_unregister completes.
231         */
232         void (*thread_detach)(THREAD_INFO_TYPE *info);
233         void (*thread_attach)(THREAD_INFO_TYPE *info);
234         gboolean (*mono_method_is_critical) (void *method);
235         gboolean (*ip_in_critical_region) (MonoDomain *domain, gpointer ip);
236         gboolean (*mono_thread_in_critical_region) (THREAD_INFO_TYPE *info);
237 } MonoThreadInfoCallbacks;
238
239 typedef struct {
240         void (*setup_async_callback) (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data);
241         gboolean (*thread_state_init_from_sigctx) (MonoThreadUnwindState *state, void *sigctx);
242         gboolean (*thread_state_init_from_handle) (MonoThreadUnwindState *tctx, MonoThreadInfo *info);
243         void (*thread_state_init) (MonoThreadUnwindState *tctx);
244 } MonoThreadInfoRuntimeCallbacks;
245
246 //Not using 0 and 1 to ensure callbacks are not returning bad data
247 typedef enum {
248         MonoResumeThread = 0x1234,
249         KeepSuspended = 0x4321,
250 } SuspendThreadResult;
251
252 typedef SuspendThreadResult (*MonoSuspendThreadCallback) (THREAD_INFO_TYPE *info, gpointer user_data);
253
254 static inline gboolean
255 mono_threads_filter_tools_threads (THREAD_INFO_TYPE *info)
256 {
257         return !((MonoThreadInfo*)info)->tools_thread;
258 }
259
260 /*
261 Requires the world to be stoped
262 */
263 #define FOREACH_THREAD(thread) \
264         MONO_LLS_FOREACH_FILTERED (mono_thread_info_list_head (), THREAD_INFO_TYPE, thread, mono_threads_filter_tools_threads)
265
266 #define FOREACH_THREAD_END \
267         MONO_LLS_FOREACH_END
268
269 /*
270 Snapshot iteration.
271 */
272 #define FOREACH_THREAD_SAFE(thread) \
273         MONO_LLS_FOREACH_FILTERED_SAFE (mono_thread_info_list_head (), THREAD_INFO_TYPE, thread, mono_threads_filter_tools_threads)
274
275 #define FOREACH_THREAD_SAFE_END \
276         MONO_LLS_FOREACH_SAFE_END
277
278 static inline MonoNativeThreadId
279 mono_thread_info_get_tid (THREAD_INFO_TYPE *info)
280 {
281         return MONO_UINT_TO_NATIVE_THREAD_ID (((MonoThreadInfo*) info)->node.key);
282 }
283
284 static inline void
285 mono_thread_info_set_tid (THREAD_INFO_TYPE *info, MonoNativeThreadId tid)
286 {
287         ((MonoThreadInfo*) info)->node.key = (uintptr_t) MONO_NATIVE_THREAD_ID_TO_UINT (tid);
288 }
289
290 /*
291  * @thread_info_size is sizeof (GcThreadInfo), a struct the GC defines to make it possible to have
292  * a single block with info from both camps. 
293  */
294 void
295 mono_threads_init (MonoThreadInfoCallbacks *callbacks, size_t thread_info_size);
296
297 void
298 mono_threads_runtime_init (MonoThreadInfoRuntimeCallbacks *callbacks);
299
300 MonoThreadInfoRuntimeCallbacks *
301 mono_threads_get_runtime_callbacks (void);
302
303 int
304 mono_thread_info_register_small_id (void);
305
306 THREAD_INFO_TYPE *
307 mono_thread_info_attach (void *baseptr);
308
309 MONO_API void
310 mono_thread_info_detach (void);
311
312 gboolean
313 mono_thread_info_is_exiting (void);
314
315 THREAD_INFO_TYPE *
316 mono_thread_info_current (void);
317
318 THREAD_INFO_TYPE*
319 mono_thread_info_current_unchecked (void);
320
321 int
322 mono_thread_info_get_small_id (void);
323
324 MonoLinkedListSet*
325 mono_thread_info_list_head (void);
326
327 THREAD_INFO_TYPE*
328 mono_thread_info_lookup (MonoNativeThreadId id);
329
330 gboolean
331 mono_thread_info_resume (MonoNativeThreadId tid);
332
333 void
334 mono_thread_info_safe_suspend_and_run (MonoNativeThreadId id, gboolean interrupt_kernel, MonoSuspendThreadCallback callback, gpointer user_data);
335
336 void
337 mono_thread_info_setup_async_call (THREAD_INFO_TYPE *info, void (*target_func)(void*), void *user_data);
338
339 void
340 mono_thread_info_suspend_lock (void);
341
342 void
343 mono_thread_info_suspend_unlock (void);
344
345 void
346 mono_thread_info_abort_socket_syscall_for_close (MonoNativeThreadId tid);
347
348 void
349 mono_thread_info_set_is_async_context (gboolean async_context);
350
351 gboolean
352 mono_thread_info_is_async_context (void);
353
354 void
355 mono_thread_info_get_stack_bounds (guint8 **staddr, size_t *stsize);
356
357 MONO_API gboolean
358 mono_thread_info_yield (void);
359
360 gint
361 mono_thread_info_sleep (guint32 ms, gboolean *alerted);
362
363 gint
364 mono_thread_info_usleep (guint64 us);
365
366 gpointer
367 mono_thread_info_tls_get (THREAD_INFO_TYPE *info, MonoTlsKey key);
368
369 void
370 mono_thread_info_tls_set (THREAD_INFO_TYPE *info, MonoTlsKey key, gpointer value);
371
372 void
373 mono_thread_info_exit (gsize exit_code);
374
375 void
376 mono_thread_info_install_interrupt (void (*callback) (gpointer data), gpointer data, gboolean *interrupted);
377
378 void
379 mono_thread_info_uninstall_interrupt (gboolean *interrupted);
380
381 MonoThreadInfoInterruptToken*
382 mono_thread_info_prepare_interrupt (THREAD_INFO_TYPE *info);
383
384 void
385 mono_thread_info_finish_interrupt (MonoThreadInfoInterruptToken *token);
386
387 void
388 mono_thread_info_self_interrupt (void);
389
390 void
391 mono_thread_info_clear_self_interrupt (void);
392
393 gboolean
394 mono_thread_info_is_interrupt_state (THREAD_INFO_TYPE *info);
395
396 void
397 mono_thread_info_describe_interrupt_token (THREAD_INFO_TYPE *info, GString *text);
398
399 gboolean
400 mono_thread_info_is_live (THREAD_INFO_TYPE *info);
401
402 MonoThreadHandle*
403 mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize * const stack_size, MonoNativeThreadId *out_tid);
404
405 int
406 mono_threads_get_max_stack_size (void);
407
408 MonoThreadHandle*
409 mono_threads_open_thread_handle (MonoThreadHandle *handle);
410
411 void
412 mono_threads_close_thread_handle (MonoThreadHandle *handle);
413
414 MONO_API void
415 mono_threads_attach_tools_thread (void);
416
417
418 #if !defined(HOST_WIN32)
419
420 /*Use this instead of pthread_kill */
421 int
422 mono_threads_pthread_kill (THREAD_INFO_TYPE *info, int signum);
423
424 #endif /* !defined(HOST_WIN32) */
425
426 /* Internal API between mono-threads and its backends. */
427
428 /* Backend functions - a backend must implement all of the following */
429 /*
430 This is called very early in the runtime, it cannot access any runtime facilities.
431
432 */
433 void mono_threads_suspend_init (void); //ok
434
435 void mono_threads_suspend_init_signals (void);
436
437 void mono_threads_coop_init (void);
438
439 /*
440 This begins async suspend. This function must do the following:
441
442 -Ensure the target will EINTR any syscalls if @interrupt_kernel is true
443 -Call mono_threads_transition_finish_async_suspend as part of its async suspend.
444 -Register the thread for pending suspend with mono_threads_add_to_pending_operation_set if needed.
445
446 If begin suspend fails the thread must be left uninterrupted and resumed.
447 */
448 gboolean mono_threads_suspend_begin_async_suspend (THREAD_INFO_TYPE *info, gboolean interrupt_kernel);
449
450 /*
451 This verifies the outcome of an async suspend operation.
452
453 Some targets, such as posix, verify suspend results assynchronously. Suspend results must be
454 available (in a non blocking way) after mono_threads_wait_pending_operations completes.
455 */
456 gboolean mono_threads_suspend_check_suspend_result (THREAD_INFO_TYPE *info);
457
458 /*
459 This begins async resume. This function must do the following:
460
461 - Install an async target if one was requested.
462 - Notify the target to resume.
463 - Register the thread for pending ack with mono_threads_add_to_pending_operation_set if needed.
464 */
465 gboolean mono_threads_suspend_begin_async_resume (THREAD_INFO_TYPE *info);
466
467 void mono_threads_suspend_register (THREAD_INFO_TYPE *info); //ok
468 void mono_threads_suspend_free (THREAD_INFO_TYPE *info);
469 void mono_threads_suspend_abort_syscall (THREAD_INFO_TYPE *info);
470 gboolean mono_threads_suspend_needs_abort_syscall (void);
471 gint mono_threads_suspend_search_alternative_signal (void);
472 gint mono_threads_suspend_get_suspend_signal (void);
473 gint mono_threads_suspend_get_restart_signal (void);
474 gint mono_threads_suspend_get_abort_signal (void);
475
476 int mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid);
477 void mono_threads_platform_get_stack_bounds (guint8 **staddr, size_t *stsize);
478 gboolean mono_threads_platform_yield (void);
479 void mono_threads_platform_exit (gsize exit_code);
480
481 void mono_threads_coop_begin_global_suspend (void);
482 void mono_threads_coop_end_global_suspend (void);
483
484 MONO_API MonoNativeThreadId
485 mono_native_thread_id_get (void);
486
487 MONO_API gboolean
488 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2);
489
490 MONO_API gboolean
491 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg);
492
493 MONO_API void
494 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name);
495
496 MONO_API gboolean
497 mono_native_thread_join (MonoNativeThreadId tid);
498
499 /*Mach specific internals */
500 void mono_threads_init_dead_letter (void);
501 void mono_threads_install_dead_letter (void);
502
503 /* mono-threads internal API used by the backends. */
504 /*
505 This tells the suspend initiator that we completed suspend and will now be waiting for resume.
506 */
507 void mono_threads_notify_initiator_of_suspend (THREAD_INFO_TYPE* info);
508 /*
509 This tells the resume initiator that we completed resume duties and will return to runnable state.
510 */
511 void mono_threads_notify_initiator_of_resume (THREAD_INFO_TYPE* info);
512
513 /*
514 This tells the resume initiator that we completed abort duties and will return to previous state.
515 */
516 void mono_threads_notify_initiator_of_abort (THREAD_INFO_TYPE* info);
517
518 /* Thread state machine functions */
519
520 typedef enum {
521         ResumeError,
522         ResumeOk,
523         ResumeInitSelfResume,
524         ResumeInitAsyncResume,
525         ResumeInitBlockingResume,
526 } MonoResumeResult;
527
528 typedef enum {
529         SelfSuspendResumed,
530         SelfSuspendWait,
531         SelfSuspendNotifyAndWait,
532 } MonoSelfSupendResult;
533
534 typedef enum {
535         AsyncSuspendAlreadySuspended,
536         AsyncSuspendWait,
537         AsyncSuspendInitSuspend,
538         AsyncSuspendBlocking,
539 } MonoRequestAsyncSuspendResult;
540
541 typedef enum {
542         DoBlockingContinue, //in blocking mode, continue
543         DoBlockingPollAndRetry, //async suspend raced blocking and won, pool and retry
544 } MonoDoBlockingResult;
545
546 typedef enum {
547         DoneBlockingOk, //exited blocking fine
548         DoneBlockingWait, //thread should end suspended
549 } MonoDoneBlockingResult;
550
551
552 typedef enum {
553         AbortBlockingIgnore, //Ignore
554         AbortBlockingIgnoreAndPoll, //Ignore and poll
555         AbortBlockingOk, //Abort worked
556         AbortBlockingWait, //Abort worked, but should wait for resume
557 } MonoAbortBlockingResult;
558
559
560 void mono_threads_transition_attach (THREAD_INFO_TYPE* info);
561 gboolean mono_threads_transition_detach (THREAD_INFO_TYPE *info);
562 MonoRequestAsyncSuspendResult mono_threads_transition_request_async_suspension (THREAD_INFO_TYPE *info);
563 MonoSelfSupendResult mono_threads_transition_state_poll (THREAD_INFO_TYPE *info);
564 MonoResumeResult mono_threads_transition_request_resume (THREAD_INFO_TYPE* info);
565 gboolean mono_threads_transition_finish_async_suspend (THREAD_INFO_TYPE* info);
566 MonoDoBlockingResult mono_threads_transition_do_blocking (THREAD_INFO_TYPE* info);
567 MonoDoneBlockingResult mono_threads_transition_done_blocking (THREAD_INFO_TYPE* info);
568 MonoAbortBlockingResult mono_threads_transition_abort_blocking (THREAD_INFO_TYPE* info);
569
570 MonoThreadUnwindState* mono_thread_info_get_suspend_state (THREAD_INFO_TYPE *info);
571
572 gpointer
573 mono_threads_enter_gc_unsafe_region_cookie (void);
574
575
576 void mono_thread_info_wait_for_resume (THREAD_INFO_TYPE *info);
577 /* Advanced suspend API, used for suspending multiple threads as once. */
578 gboolean mono_thread_info_is_running (THREAD_INFO_TYPE *info);
579 gboolean mono_thread_info_is_live (THREAD_INFO_TYPE *info);
580 int mono_thread_info_suspend_count (THREAD_INFO_TYPE *info);
581 int mono_thread_info_current_state (THREAD_INFO_TYPE *info);
582 const char* mono_thread_state_name (int state);
583
584 gboolean mono_thread_info_in_critical_location (THREAD_INFO_TYPE *info);
585 gboolean mono_thread_info_begin_suspend (THREAD_INFO_TYPE *info);
586 gboolean mono_thread_info_begin_resume (THREAD_INFO_TYPE *info);
587
588 void mono_threads_add_to_pending_operation_set (THREAD_INFO_TYPE* info); //XXX rename to something to reflect the fact that this is used for both suspend and resume
589 gboolean mono_threads_wait_pending_operations (void);
590 void mono_threads_begin_global_suspend (void);
591 void mono_threads_end_global_suspend (void);
592
593 gboolean
594 mono_thread_info_is_current (THREAD_INFO_TYPE *info);
595
596 typedef enum {
597         MONO_THREAD_INFO_WAIT_RET_SUCCESS_0   =  0,
598         MONO_THREAD_INFO_WAIT_RET_ALERTED     = -1,
599         MONO_THREAD_INFO_WAIT_RET_TIMEOUT     = -2,
600         MONO_THREAD_INFO_WAIT_RET_FAILED      = -3,
601 } MonoThreadInfoWaitRet;
602
603 MonoThreadInfoWaitRet
604 mono_thread_info_wait_one_handle (MonoThreadHandle *handle, guint32 timeout, gboolean alertable);
605
606 MonoThreadInfoWaitRet
607 mono_thread_info_wait_multiple_handle (MonoThreadHandle **thread_handles, gsize nhandles, MonoOSEvent *background_change_event, gboolean waitall, guint32 timeout, gboolean alertable);
608
609 #endif /* __MONO_THREADS_H__ */