Ruby 4.1.0dev (2026-09-07 revision b57404b461ba8bf34e802d86b0db78388216e182)
thread_pthread.c (b57404b461ba8bf34e802d86b0db78388216e182)
1/* -*-c-*- */
2/**********************************************************************
3
4 thread_pthread.c -
5
6 $Author$
7
8 Copyright (C) 2004-2007 Koichi Sasada
9
10**********************************************************************/
11
12#ifdef THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
13
14#include "internal/gc.h"
15#include "internal/sanitizers.h"
16
17#ifdef HAVE_SYS_RESOURCE_H
18#include <sys/resource.h>
19#endif
20#ifdef HAVE_THR_STKSEGMENT
21#include <thread.h>
22#endif
23#if defined(HAVE_FCNTL_H)
24#include <fcntl.h>
25#elif defined(HAVE_SYS_FCNTL_H)
26#include <sys/fcntl.h>
27#endif
28#ifdef HAVE_SYS_PRCTL_H
29#include <sys/prctl.h>
30#endif
31#if defined(HAVE_SYS_TIME_H)
32#include <sys/time.h>
33#endif
34#if defined(__HAIKU__)
35#include <kernel/OS.h>
36#endif
37#ifdef __linux__
38#include <sys/syscall.h> /* for SYS_gettid */
39#endif
40#include <time.h>
41#include <signal.h>
42
43#include "probes.h"
44
45#if defined __APPLE__
46# include <AvailabilityMacros.h>
47#endif
48
49#if defined(HAVE_SYS_EVENTFD_H) && defined(HAVE_EVENTFD)
50# define USE_EVENTFD (1)
51# include <sys/eventfd.h>
52#else
53# define USE_EVENTFD (0)
54#endif
55
56#if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && \
57 defined(CLOCK_REALTIME) && defined(CLOCK_MONOTONIC) && \
58 defined(HAVE_CLOCK_GETTIME)
59static pthread_condattr_t condattr_mono;
60static pthread_condattr_t *condattr_monotonic = &condattr_mono;
61#else
62static const void *const condattr_monotonic = NULL;
63#endif
64
65// Whether native_cond_timedwait() takes an rb_hrtime_t deadline as is. It
66// does when the condvar counts in the same clock rb_hrtime_now() reads;
67// otherwise the caller has to restate the deadline in the condvar's clock.
68#define RB_NATIVE_COND_HRTIME_DEADLINE_P() (condattr_monotonic != NULL)
69
70/* A retiring shared native thread frees its own context while the threads it
71 * parked are still suspended with that context as their target. */
72#define COROUTINE_TARGET_MAY_BE_FREED 1
73
74#include COROUTINE_H
75
76#ifndef HAVE_SYS_EVENT_H
77#define HAVE_SYS_EVENT_H 0
78#endif
79
80#ifndef HAVE_SYS_EPOLL_H
81#define HAVE_SYS_EPOLL_H 0
82#else
83// force setting for debug
84// #undef HAVE_SYS_EPOLL_H
85// #define HAVE_SYS_EPOLL_H 0
86#endif
87
88#ifndef USE_MN_THREADS
89 #if defined(__EMSCRIPTEN__) || defined(COROUTINE_PTHREAD_CONTEXT)
90 // on __EMSCRIPTEN__ provides epoll* declarations, but no implementations.
91 // on COROUTINE_PTHREAD_CONTEXT, it doesn't worth to use it.
92 #define USE_MN_THREADS 0
93 #elif HAVE_SYS_EPOLL_H
94 #include <sys/epoll.h>
95 #ifdef EPOLLONESHOT
96 #define USE_MN_THREADS 1
97 #else
98 // the scheduler arms io fds with EPOLLONESHOT (Linux 2.6.2)
99 #define USE_MN_THREADS 0
100 #endif
101 #elif HAVE_SYS_EVENT_H
102 #include <sys/event.h>
103 #define USE_MN_THREADS 1
104 #else
105 #define USE_MN_THREADS 0
106 #endif
107#endif
108
109#ifdef HAVE_SCHED_YIELD
110#define native_thread_yield() (void)sched_yield()
111#else
112#define native_thread_yield() ((void)0)
113#endif
114
115// native thread wrappers
116
117#define NATIVE_MUTEX_LOCK_DEBUG 0
118#define NATIVE_MUTEX_LOCK_DEBUG_YIELD 0
119
120static void
121mutex_debug(const char *msg, void *lock)
122{
123 if (NATIVE_MUTEX_LOCK_DEBUG) {
124 int r;
125 static pthread_mutex_t dbglock = PTHREAD_MUTEX_INITIALIZER;
126
127 if ((r = pthread_mutex_lock(&dbglock)) != 0) {exit(EXIT_FAILURE);}
128 fprintf(stdout, "%s: %p\n", msg, lock);
129 if ((r = pthread_mutex_unlock(&dbglock)) != 0) {exit(EXIT_FAILURE);}
130 }
131}
132
133void
134rb_native_mutex_lock(pthread_mutex_t *lock)
135{
136 int r;
137#if NATIVE_MUTEX_LOCK_DEBUG_YIELD
138 native_thread_yield();
139#endif
140 mutex_debug("lock", lock);
141 if ((r = pthread_mutex_lock(lock)) != 0) {
142 rb_bug_errno("pthread_mutex_lock", r);
143 }
144}
145
146void
147rb_native_mutex_unlock(pthread_mutex_t *lock)
148{
149 int r;
150 mutex_debug("unlock", lock);
151 if ((r = pthread_mutex_unlock(lock)) != 0) {
152 rb_bug_errno("pthread_mutex_unlock", r);
153 }
154}
155
156int
157rb_native_mutex_trylock(pthread_mutex_t *lock)
158{
159 int r;
160 mutex_debug("trylock", lock);
161 if ((r = pthread_mutex_trylock(lock)) != 0) {
162 if (r == EBUSY) {
163 return EBUSY;
164 }
165 else {
166 rb_bug_errno("pthread_mutex_trylock", r);
167 }
168 }
169 return 0;
170}
171
172void
173rb_native_mutex_initialize(pthread_mutex_t *lock)
174{
175 int r = pthread_mutex_init(lock, 0);
176 mutex_debug("init", lock);
177 if (r != 0) {
178 rb_bug_errno("pthread_mutex_init", r);
179 }
180}
181
182void
183rb_native_mutex_destroy(pthread_mutex_t *lock)
184{
185 int r = pthread_mutex_destroy(lock);
186 mutex_debug("destroy", lock);
187 if (r != 0) {
188 rb_bug_errno("pthread_mutex_destroy", r);
189 }
190}
191
192void
193rb_native_cond_initialize(rb_nativethread_cond_t *cond)
194{
195 int r = pthread_cond_init(cond, condattr_monotonic);
196 if (r != 0) {
197 rb_bug_errno("pthread_cond_init", r);
198 }
199}
200
201void
202rb_native_cond_destroy(rb_nativethread_cond_t *cond)
203{
204 int r = pthread_cond_destroy(cond);
205 if (r != 0) {
206 rb_bug_errno("pthread_cond_destroy", r);
207 }
208}
209
210/*
211 * In OS X 10.7 (Lion), pthread_cond_signal and pthread_cond_broadcast return
212 * EAGAIN after retrying 8192 times. You can see them in the following page:
213 *
214 * http://www.opensource.apple.com/source/Libc/Libc-763.11/pthreads/pthread_cond.c
215 *
216 * The following rb_native_cond_signal and rb_native_cond_broadcast functions
217 * need to retrying until pthread functions don't return EAGAIN.
218 */
219
220void
221rb_native_cond_signal(rb_nativethread_cond_t *cond)
222{
223 int r;
224 do {
225 r = pthread_cond_signal(cond);
226 } while (r == EAGAIN);
227 if (r != 0) {
228 rb_bug_errno("pthread_cond_signal", r);
229 }
230}
231
232void
233rb_native_cond_broadcast(rb_nativethread_cond_t *cond)
234{
235 int r;
236 do {
237 r = pthread_cond_broadcast(cond);
238 } while (r == EAGAIN);
239 if (r != 0) {
240 rb_bug_errno("rb_native_cond_broadcast", r);
241 }
242}
243
244void
245rb_native_cond_wait(rb_nativethread_cond_t *cond, pthread_mutex_t *mutex)
246{
247 int r = pthread_cond_wait(cond, mutex);
248 if (r != 0) {
249 rb_bug_errno("pthread_cond_wait", r);
250 }
251}
252
253static int
254native_cond_timedwait(rb_nativethread_cond_t *cond, pthread_mutex_t *mutex, const rb_hrtime_t *abs)
255{
256 int r;
257 struct timespec ts;
258
259 /*
260 * An old Linux may return EINTR. Even though POSIX says
261 * "These functions shall not return an error code of [EINTR]".
262 * http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_timedwait.html
263 * Let's hide it from arch generic code.
264 */
265 do {
266 rb_hrtime2timespec(&ts, abs);
267 r = pthread_cond_timedwait(cond, mutex, &ts);
268 } while (r == EINTR);
269
270 if (r != 0 && r != ETIMEDOUT) {
271 rb_bug_errno("pthread_cond_timedwait", r);
272 }
273
274 return r;
275}
276
277static rb_hrtime_t
278native_cond_timeout(rb_nativethread_cond_t *cond, const rb_hrtime_t rel)
279{
280 if (condattr_monotonic) {
281 return rb_hrtime_add(rb_hrtime_now(), rel);
282 }
283 else {
284 struct timespec ts;
285
286 rb_timespec_now(&ts);
287 return rb_hrtime_add(rb_timespec2hrtime(&ts), rel);
288 }
289}
290
291void
292rb_native_cond_timedwait(rb_nativethread_cond_t *cond, pthread_mutex_t *mutex, unsigned long msec)
293{
294 rb_hrtime_t hrmsec = native_cond_timeout(cond, RB_HRTIME_PER_MSEC * msec);
295 native_cond_timedwait(cond, mutex, &hrmsec);
296}
297
298// thread scheduling
299
300static rb_internal_thread_event_hook_t *rb_internal_thread_event_hooks = NULL;
301static void rb_thread_execute_hooks(rb_event_flag_t event, rb_thread_t *th);
302
303#if 0
304static const char *
305event_name(rb_event_flag_t event)
306{
307 switch (event) {
309 return "STARTED";
311 return "READY";
313 return "RESUMED";
315 return "SUSPENDED";
317 return "EXITED";
318 }
319 return "no-event";
320}
321
322#define RB_INTERNAL_THREAD_HOOK(event, th) \
323 if (UNLIKELY(rb_internal_thread_event_hooks)) { \
324 fprintf(stderr, "[thread=%"PRIxVALUE"] %s in %s (%s:%d)\n", th->self, event_name(event), __func__, __FILE__, __LINE__); \
325 rb_thread_execute_hooks(event, th); \
326 }
327#else
328#define RB_INTERNAL_THREAD_HOOK(event, th) if (UNLIKELY(rb_internal_thread_event_hooks)) { rb_thread_execute_hooks(event, th); }
329#endif
330
331static rb_serial_t current_fork_gen = 1; /* We can't use GET_VM()->fork_gen */
332
333#if defined(SIGVTALRM) && !defined(__EMSCRIPTEN__)
334# define USE_UBF_LIST 1
335#endif
336
337#if USE_MN_THREADS
338static void nt_machine_stack_atfork(void);
339
340// A coroutine thread's execution context: the coroutine_context (first, so
341// th->sched.context points at the whole block) plus what is needed to free
342// it without the rb_thread_t. Owned by the execution: the dying thread marks
343// it dead before its final transfer, and whichever context RESUMES from that
344// transfer frees it -- the resume itself proves the transfer's register save
345// into this block has completed, so no further synchronization is needed.
346struct rb_thread_context {
347 struct coroutine_context co; // must be first
348 void *stack; // the coroutine machine stack (pool stack)
349 struct rb_native_thread *nt; // final transfer target, stashed at termination
350 bool dead;
351};
352
353static bool thread_sched_reclaim(struct coroutine_context *dead_co);
354#endif
355
356
357#ifdef RB_THREAD_T_HAS_NATIVE_ID
358static int
359get_native_thread_id(void)
360{
361#ifdef __linux__
362 return (int)syscall(SYS_gettid);
363#elif defined(__FreeBSD__)
364 return pthread_getthreadid_np();
365#endif
366}
367#endif
368
369
370#ifdef RB_THREAD_LOCAL_SPECIFIER
371static RB_THREAD_LOCAL_SPECIFIER rb_thread_t *ruby_native_thread;
372#else
373static pthread_key_t ruby_native_thread_key;
374#endif
375
376static void
377null_func(int i)
378{
379 /* null */
380 // This function can be called from signal handler
381 // RUBY_DEBUG_LOG("i:%d", i);
382}
383
385ruby_thread_from_native(void)
386{
387#ifdef RB_THREAD_LOCAL_SPECIFIER
388 return ruby_native_thread;
389#else
390 return pthread_getspecific(ruby_native_thread_key);
391#endif
392}
393
394int
395ruby_thread_set_native(rb_thread_t *th)
396{
397 if (th) {
398#ifdef USE_UBF_LIST
399 ccan_list_node_init(&th->sched.node.ubf);
400#endif
401 }
402
403 // setup TLS
404
405 if (th && th->ec) {
406 rb_ractor_set_current_ec(th->ractor, th->ec);
407 }
408#ifdef RB_THREAD_LOCAL_SPECIFIER
409 ruby_native_thread = th;
410 return 1;
411#else
412 return pthread_setspecific(ruby_native_thread_key, th) == 0;
413#endif
414}
415
416static void native_thread_setup(struct rb_native_thread *nt);
417static void native_thread_setup_on_thread(struct rb_native_thread *nt);
418
419// Internal cache of page size:
420static size_t RB_THREAD_PAGE_SIZE;
421
422void
423Init_native_thread(rb_thread_t *main_th)
424{
425 // Get the system page size for later use in stack allocation and stack overflow checks:
426 RB_THREAD_PAGE_SIZE = sysconf(_SC_PAGESIZE);
427
428#if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK)
429 if (condattr_monotonic) {
430 int r = pthread_condattr_init(condattr_monotonic);
431 if (r == 0) {
432 r = pthread_condattr_setclock(condattr_monotonic, CLOCK_MONOTONIC);
433 }
434 if (r) condattr_monotonic = NULL;
435 }
436#endif
437
438#ifndef RB_THREAD_LOCAL_SPECIFIER
439 if (pthread_key_create(&ruby_native_thread_key, 0) == EAGAIN) {
440 rb_bug("pthread_key_create failed (ruby_native_thread_key)");
441 }
442 if (pthread_key_create(&ruby_current_ec_key, 0) == EAGAIN) {
443 rb_bug("pthread_key_create failed (ruby_current_ec_key)");
444 }
445#endif
446 ruby_posix_signal(SIGVTALRM, null_func);
447
448 // setup vm
449 rb_vm_t *vm = main_th->vm;
450 thread_sched_init_vm(vm);
451
452 // setup main thread
453 main_th->nt->thread_id = pthread_self();
454 main_th->nt->serial = 1;
455#ifdef RUBY_NT_SERIAL
456 ruby_nt_serial = 1;
457#endif
458 ruby_thread_set_native(main_th);
459 native_thread_setup(main_th->nt);
460 native_thread_setup_on_thread(main_th->nt);
461
462 TH_SCHED(main_th)->running = main_th;
463 main_th->has_dedicated_nt = 1;
464
465 // setup main NT (before the record below: its kind decides where it goes)
466 main_th->nt->dedicated = 1;
467 main_th->nt->running_thread = main_th;
468 main_th->nt->vm = vm;
469
470 thread_sched_setup_running_threads(TH_SCHED(main_th), main_th->ractor, vm, main_th, NULL);
471
472 // setup mn
473#if USE_RUBY_DEBUG_LOG
474 vm->ractor.sched.dnt_cnt = 1;
475#endif
476}
477
478
479static void
480native_thread_destroy_atfork(struct rb_native_thread *nt)
481{
482 if (nt) {
483 /* We can't call rb_native_cond_destroy here because according to the
484 * specs of pthread_cond_destroy:
485 *
486 * Attempting to destroy a condition variable upon which other threads
487 * are currently blocked results in undefined behavior.
488 *
489 * Specifically, glibc's pthread_cond_destroy waits on all the other
490 * listeners. Since after forking all the threads are dead, the condition
491 * variable's listeners will never wake up, so it will hang forever.
492 */
493
494 RB_ALTSTACK_FREE(nt->altstack);
495 SIZED_FREE(nt->nt_context);
496 SIZED_FREE(nt);
497 }
498}
499
500static void
501native_thread_destroy(struct rb_native_thread *nt)
502{
503 if (nt) {
504 rb_native_cond_destroy(&nt->readyq);
505 rb_native_mutex_destroy(&nt->running_th_lock);
506
507 native_thread_destroy_atfork(nt);
508 }
509}
510
511// A retiring snt frees its own rb_native_thread as it exits. Disarm the
512// altstack registration first: a signal between the free and the thread's
513// end must not run on the freed block.
514static void
515native_thread_destroy_self(struct rb_native_thread *nt)
516{
517#ifdef USE_SIGALTSTACK
518 stack_t disable = {0};
519 disable.ss_flags = SS_DISABLE;
520 sigaltstack(&disable, NULL);
521#endif
522 native_thread_destroy(nt);
523}
524
525#if defined HAVE_PTHREAD_GETATTR_NP || defined HAVE_PTHREAD_ATTR_GET_NP
526#define STACKADDR_AVAILABLE 1
527#elif defined HAVE_PTHREAD_GET_STACKADDR_NP && defined HAVE_PTHREAD_GET_STACKSIZE_NP
528#define STACKADDR_AVAILABLE 1
529#undef MAINSTACKADDR_AVAILABLE
530#define MAINSTACKADDR_AVAILABLE 1
531void *pthread_get_stackaddr_np(pthread_t);
532size_t pthread_get_stacksize_np(pthread_t);
533#elif defined HAVE_THR_STKSEGMENT || defined HAVE_PTHREAD_STACKSEG_NP
534#define STACKADDR_AVAILABLE 1
535#elif defined HAVE_PTHREAD_GETTHRDS_NP
536#define STACKADDR_AVAILABLE 1
537#elif defined __HAIKU__
538#define STACKADDR_AVAILABLE 1
539#endif
540
541#ifndef MAINSTACKADDR_AVAILABLE
542# ifdef STACKADDR_AVAILABLE
543# define MAINSTACKADDR_AVAILABLE 1
544# else
545# define MAINSTACKADDR_AVAILABLE 0
546# endif
547#endif
548#if MAINSTACKADDR_AVAILABLE && !defined(get_main_stack)
549# define get_main_stack(addr, size) get_stack(addr, size)
550#endif
551
552#ifdef STACKADDR_AVAILABLE
553/*
554 * Get the initial address and size of current thread's stack
555 */
556static int
557get_stack(void **addr, size_t *size)
558{
559#define CHECK_ERR(expr) \
560 {int err = (expr); if (err) return err;}
561#ifdef HAVE_PTHREAD_GETATTR_NP /* Linux */
562 pthread_attr_t attr;
563 size_t guard = 0;
564 STACK_GROW_DIR_DETECTION;
565 CHECK_ERR(pthread_getattr_np(pthread_self(), &attr));
566# ifdef HAVE_PTHREAD_ATTR_GETSTACK
567 CHECK_ERR(pthread_attr_getstack(&attr, addr, size));
568 STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size));
569# else
570 CHECK_ERR(pthread_attr_getstackaddr(&attr, addr));
571 CHECK_ERR(pthread_attr_getstacksize(&attr, size));
572# endif
573# ifdef HAVE_PTHREAD_ATTR_GETGUARDSIZE
574 CHECK_ERR(pthread_attr_getguardsize(&attr, &guard));
575# else
576 guard = RB_THREAD_PAGE_SIZE;
577# endif
578 *size -= guard;
579 pthread_attr_destroy(&attr);
580#elif defined HAVE_PTHREAD_ATTR_GET_NP /* FreeBSD, DragonFly BSD, NetBSD */
581 pthread_attr_t attr;
582 CHECK_ERR(pthread_attr_init(&attr));
583 CHECK_ERR(pthread_attr_get_np(pthread_self(), &attr));
584# ifdef HAVE_PTHREAD_ATTR_GETSTACK
585 CHECK_ERR(pthread_attr_getstack(&attr, addr, size));
586# else
587 CHECK_ERR(pthread_attr_getstackaddr(&attr, addr));
588 CHECK_ERR(pthread_attr_getstacksize(&attr, size));
589# endif
590 STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size));
591 pthread_attr_destroy(&attr);
592#elif (defined HAVE_PTHREAD_GET_STACKADDR_NP && defined HAVE_PTHREAD_GET_STACKSIZE_NP) /* MacOS X */
593 pthread_t th = pthread_self();
594 *addr = pthread_get_stackaddr_np(th);
595 *size = pthread_get_stacksize_np(th);
596#elif defined HAVE_THR_STKSEGMENT || defined HAVE_PTHREAD_STACKSEG_NP
597 stack_t stk;
598# if defined HAVE_THR_STKSEGMENT /* Solaris */
599 CHECK_ERR(thr_stksegment(&stk));
600# else /* OpenBSD */
601 CHECK_ERR(pthread_stackseg_np(pthread_self(), &stk));
602# endif
603 *addr = stk.ss_sp;
604 *size = stk.ss_size;
605#elif defined HAVE_PTHREAD_GETTHRDS_NP /* AIX */
606 pthread_t th = pthread_self();
607 struct __pthrdsinfo thinfo;
608 char reg[256];
609 int regsiz=sizeof(reg);
610 CHECK_ERR(pthread_getthrds_np(&th, PTHRDSINFO_QUERY_ALL,
611 &thinfo, sizeof(thinfo),
612 &reg, &regsiz));
613 *addr = thinfo.__pi_stackaddr;
614 /* Must not use thinfo.__pi_stacksize for size.
615 It is around 3KB smaller than the correct size
616 calculated by thinfo.__pi_stackend - thinfo.__pi_stackaddr. */
617 *size = thinfo.__pi_stackend - thinfo.__pi_stackaddr;
618 STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size));
619#elif defined __HAIKU__
620 thread_info info;
621 STACK_GROW_DIR_DETECTION;
622 CHECK_ERR(get_thread_info(find_thread(NULL), &info));
623 *addr = info.stack_base;
624 *size = (uintptr_t)info.stack_end - (uintptr_t)info.stack_base;
625 STACK_DIR_UPPER((void)0, (void)(*addr = (char *)*addr + *size));
626#else
627#error STACKADDR_AVAILABLE is defined but not implemented.
628#endif
629 return 0;
630#undef CHECK_ERR
631}
632#endif
633
634static struct {
635 rb_nativethread_id_t id;
636 size_t stack_maxsize;
637 VALUE *stack_start;
638} native_main_thread;
639
640#ifdef STACK_END_ADDRESS
641extern void *STACK_END_ADDRESS;
642#endif
643
644static void
645native_thread_init_main_thread_stack(void *addr)
646{
647 native_main_thread.id = pthread_self();
648#ifdef RUBY_ASAN_ENABLED
649 addr = asan_get_real_stack_addr((void *)addr);
650#endif
651
652#if MAINSTACKADDR_AVAILABLE
653 if (native_main_thread.stack_maxsize) return;
654 {
655 void* stackaddr;
656 size_t size;
657 if (get_main_stack(&stackaddr, &size) == 0) {
658 native_main_thread.stack_maxsize = size;
659 native_main_thread.stack_start = stackaddr;
660 goto bound_check;
661 }
662 }
663#endif
664#ifdef STACK_END_ADDRESS
665 native_main_thread.stack_start = STACK_END_ADDRESS;
666#else
667 if (!native_main_thread.stack_start ||
668 STACK_UPPER((VALUE *)(void *)&addr,
669 native_main_thread.stack_start > (VALUE *)addr,
670 native_main_thread.stack_start < (VALUE *)addr)) {
671 native_main_thread.stack_start = (VALUE *)addr;
672 }
673#endif
674 {
675#if defined(HAVE_GETRLIMIT)
676#if defined(PTHREAD_STACK_DEFAULT)
677 size_t size = PTHREAD_STACK_DEFAULT;
678#else
679 size_t size = RUBY_VM_THREAD_VM_STACK_SIZE;
680#endif
681 size_t space;
682 struct rlimit rlim;
683 STACK_GROW_DIR_DETECTION;
684 if (getrlimit(RLIMIT_STACK, &rlim) == 0) {
685 size = (size_t)rlim.rlim_cur;
686 }
687 addr = native_main_thread.stack_start;
688 if (IS_STACK_DIR_UPPER()) {
689 space = ((size_t)((char *)addr + size) / RB_THREAD_PAGE_SIZE) * RB_THREAD_PAGE_SIZE - (size_t)addr;
690 }
691 else {
692 space = (size_t)addr - ((size_t)((char *)addr - size) / RB_THREAD_PAGE_SIZE + 1) * RB_THREAD_PAGE_SIZE;
693 }
694 native_main_thread.stack_maxsize = space;
695#endif
696 }
697
698#if MAINSTACKADDR_AVAILABLE
699 bound_check:
700#endif
701 /* If addr is out of range of main-thread stack range estimation, */
702 /* it should be on co-routine (alternative stack). [Feature #2294] */
703 {
704 void *start, *end;
705 STACK_GROW_DIR_DETECTION;
706
707 if (IS_STACK_DIR_UPPER()) {
708 start = native_main_thread.stack_start;
709 end = (char *)native_main_thread.stack_start + native_main_thread.stack_maxsize;
710 }
711 else {
712 start = (char *)native_main_thread.stack_start - native_main_thread.stack_maxsize;
713 end = native_main_thread.stack_start;
714 }
715
716 if ((void *)addr < start || (void *)addr > end) {
717 /* out of range */
718 native_main_thread.stack_start = (VALUE *)addr;
719 native_main_thread.stack_maxsize = 0; /* unknown */
720 }
721 }
722}
723
724#define CHECK_ERR(expr) \
725 {int err = (expr); if (err) {rb_bug_errno(#expr, err);}}
726
727static int
728native_thread_init_stack(rb_thread_t *th, void *local_in_parent_frame)
729{
730 rb_nativethread_id_t curr = pthread_self();
731#ifdef RUBY_ASAN_ENABLED
732 local_in_parent_frame = asan_get_real_stack_addr(local_in_parent_frame);
733 th->ec->machine.asan_fake_stack_handle = asan_get_thread_fake_stack_handle();
734#endif
735
736 if (!native_main_thread.id) {
737 /* This thread is the first thread, must be the main thread -
738 * configure the native_main_thread object */
739 native_thread_init_main_thread_stack(local_in_parent_frame);
740 }
741
742 if (pthread_equal(curr, native_main_thread.id)) {
743 th->ec->machine.stack_start = native_main_thread.stack_start;
744 th->ec->machine.stack_maxsize = native_main_thread.stack_maxsize;
745 }
746 else {
747#ifdef STACKADDR_AVAILABLE
748 if (th_has_dedicated_nt(th)) {
749 void *start;
750 size_t size;
751
752 if (get_stack(&start, &size) == 0) {
753 uintptr_t diff = (uintptr_t)start - (uintptr_t)local_in_parent_frame;
754 th->ec->machine.stack_start = local_in_parent_frame;
755 th->ec->machine.stack_maxsize = size - diff;
756 }
757 }
758#else
759 rb_raise(rb_eNotImpError, "ruby engine can initialize only in the main thread");
760#endif
761 }
762
763 return 0;
764}
765
766struct nt_param {
767 rb_vm_t *vm;
768 struct rb_native_thread *nt;
769};
770
771
772static int
773native_thread_create0(struct rb_native_thread *nt)
774{
775 int err = 0;
776 pthread_attr_t attr;
777
778 const size_t stack_size = nt->vm->default_params.thread_machine_stack_size;
779
780#ifdef USE_SIGALTSTACK
781 nt->altstack = rb_allocate_sigaltstack();
782#endif
783
784 CHECK_ERR(pthread_attr_init(&attr));
785
786# ifdef PTHREAD_STACK_MIN
787 RUBY_DEBUG_LOG("stack size: %lu", (unsigned long)stack_size);
788 CHECK_ERR(pthread_attr_setstacksize(&attr, stack_size));
789# endif
790
791# ifdef HAVE_PTHREAD_ATTR_SETINHERITSCHED
792 CHECK_ERR(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
793# endif
794 CHECK_ERR(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
795
796 err = pthread_create(&nt->thread_id, &attr, nt_start, nt);
797
798 RUBY_DEBUG_LOG("nt:%d err:%d", (int)nt->serial, err);
799
800 CHECK_ERR(pthread_attr_destroy(&attr));
801
802 return err;
803}
804
805static void
806native_thread_setup(struct rb_native_thread *nt)
807{
808 // init cond
809 rb_native_cond_initialize(&nt->readyq);
810 // also for the main thread's nt: a zero-filled mutex is not usable on macOS
811 rb_native_mutex_initialize(&nt->running_th_lock);
812}
813
814static void
815native_thread_setup_on_thread(struct rb_native_thread *nt)
816{
817 // init tid
818#ifdef RB_THREAD_T_HAS_NATIVE_ID
819 nt->tid = get_native_thread_id();
820#endif
821
822 // init signal handler
823 RB_ALTSTACK_INIT(nt->altstack, nt->altstack);
824}
825
826static struct rb_native_thread *
827native_thread_alloc(void)
828{
829 struct rb_native_thread *nt = ZALLOC(struct rb_native_thread);
830 native_thread_setup(nt);
831
832#if USE_MN_THREADS
833 nt->nt_context = ruby_xmalloc(sizeof(struct coroutine_context));
834#endif
835
836#if USE_RUBY_DEBUG_LOG
837 static rb_atomic_t nt_serial = 2;
838 nt->serial = RUBY_ATOMIC_FETCH_ADD(nt_serial, 1);
839#endif
840 return nt;
841}
842
843
844
845
846#if USE_NATIVE_THREAD_PRIORITY
847
848static void
849native_thread_apply_priority(rb_thread_t *th)
850{
851#if defined(_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING > 0)
852 struct sched_param sp;
853 int policy;
854 int priority = 0 - th->priority;
855 int max, min;
856 pthread_getschedparam(th->nt->thread_id, &policy, &sp);
857 max = sched_get_priority_max(policy);
858 min = sched_get_priority_min(policy);
859
860 if (min > priority) {
861 priority = min;
862 }
863 else if (max < priority) {
864 priority = max;
865 }
866
867 sp.sched_priority = priority;
868 pthread_setschedparam(th->nt->thread_id, policy, &sp);
869#else
870 /* not touched */
871#endif
872}
873
874#endif /* USE_NATIVE_THREAD_PRIORITY */
875
876static int
877native_fd_select(int n, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout, rb_thread_t *th)
878{
879 return rb_fd_select(n, readfds, writefds, exceptfds, timeout);
880}
881
882/*
883 * Send a signal to make the target thread return from a blocking syscall.
884 * Maybe any signal is ok, but we chose SIGVTALRM (see null_func).
885 */
886static void
887native_thread_interrupt(rb_thread_t *th)
888{
889 pthread_kill(th->nt->thread_id, SIGVTALRM);
890}
891
892static int
893native_thread_default_max_cpu(void)
894{
895#if defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
896 long nprocessors = sysconf(_SC_NPROCESSORS_ONLN);
897 return (nprocessors > 0) ? (int)nprocessors : 8;
898#else
899 return 8;
900#endif
901}
902
903
904#define TT_DEBUG 0
905#define WRITE_CONST(fd, str) (void)(write((fd),(str),sizeof(str)-1)<0)
906
907void
908rb_thread_wakeup_timer_thread(int sig)
909{
910 // This function can be called from signal handlers so that
911 // pthread_mutex_lock() should not be used.
912
913 // wakeup timer thread
914 timer_thread_wakeup_force();
915
916 // interrupt main thread if main thread is available
917 if (RUBY_ATOMIC_LOAD(system_working)) {
918 rb_vm_t *vm = GET_VM();
919 rb_thread_t *main_th = vm->ractor.main_thread;
920
921 if (main_th) {
922 volatile rb_execution_context_t *main_th_ec = ACCESS_ONCE(rb_execution_context_t *, main_th->ec);
923
924 if (main_th_ec) {
925 RUBY_VM_SET_TRAP_INTERRUPT(main_th_ec);
926
927 if (vm->ubf_async_safe && main_th->unblock.func) {
928 (main_th->unblock.func)(main_th->unblock.arg);
929 }
930 }
931 }
932 }
933}
934
935#define CLOSE_INVALIDATE_PAIR(expr) \
936 close_invalidate_pair(expr,"close_invalidate: "#expr)
937static void
938close_invalidate(int *fdp, const char *msg)
939{
940 int fd = *fdp;
941
942 *fdp = -1;
943 if (close(fd) < 0) {
944 async_bug_fd(msg, errno, fd);
945 }
946}
947
948static void
949close_invalidate_pair(int fds[2], const char *msg)
950{
951 if (USE_EVENTFD && fds[0] == fds[1]) {
952 fds[1] = -1; // disable write port first
953 close_invalidate(&fds[0], msg);
954 }
955 else {
956 close_invalidate(&fds[1], msg);
957 close_invalidate(&fds[0], msg);
958 }
959}
960
961static void
962set_nonblock(int fd)
963{
964 int oflags;
965 int err;
966
967 oflags = fcntl(fd, F_GETFL);
968 if (oflags == -1)
969 rb_sys_fail(0);
970 oflags |= O_NONBLOCK;
971 err = fcntl(fd, F_SETFL, oflags);
972 if (err == -1)
973 rb_sys_fail(0);
974}
975
976/* communication pipe with timer thread and signal handler */
977static void
978setup_communication_pipe_internal(int pipes[2])
979{
980 int err;
981
982 if (pipes[0] > 0 || pipes[1] > 0) {
983 VM_ASSERT(pipes[0] > 0);
984 VM_ASSERT(pipes[1] > 0);
985 return;
986 }
987
988 /*
989 * Don't bother with eventfd on ancient Linux 2.6.22..2.6.26 which were
990 * missing EFD_* flags, they can fall back to pipe
991 */
992#if USE_EVENTFD && defined(EFD_NONBLOCK) && defined(EFD_CLOEXEC)
993 pipes[0] = pipes[1] = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);
994
995 if (pipes[0] >= 0) {
996 rb_update_max_fd(pipes[0]);
997 return;
998 }
999#endif
1000
1001 err = rb_cloexec_pipe(pipes);
1002 if (err != 0) {
1003 rb_bug("can not create communication pipe");
1004 }
1005 rb_update_max_fd(pipes[0]);
1006 rb_update_max_fd(pipes[1]);
1007 set_nonblock(pipes[0]);
1008 set_nonblock(pipes[1]);
1009}
1010
1011#if !defined(SET_CURRENT_THREAD_NAME) && defined(__linux__) && defined(PR_SET_NAME)
1012# define SET_CURRENT_THREAD_NAME(name) prctl(PR_SET_NAME, name)
1013#endif
1014
1015enum {
1016 THREAD_NAME_MAX =
1017#if defined(__linux__)
1018 16
1019#elif defined(__APPLE__)
1020/* Undocumented, and main thread seems unlimited */
1021 64
1022#else
1023 16
1024#endif
1025};
1026
1027static VALUE threadptr_invoke_proc_location(rb_thread_t *th);
1028
1029static void
1030native_set_thread_name(rb_thread_t *th)
1031{
1032#ifdef SET_CURRENT_THREAD_NAME
1033 VALUE loc;
1034 if (!NIL_P(loc = th->name)) {
1035 SET_CURRENT_THREAD_NAME(RSTRING_PTR(loc));
1036 }
1037 else if ((loc = threadptr_invoke_proc_location(th)) != Qnil) {
1038 char *name, *p;
1039 char buf[THREAD_NAME_MAX];
1040 size_t len;
1041 int n;
1042
1043 name = RSTRING_PTR(RARRAY_AREF(loc, 0));
1044 p = strrchr(name, '/'); /* show only the basename of the path. */
1045 if (p && p[1])
1046 name = p + 1;
1047
1048 n = snprintf(buf, sizeof(buf), "%s:%d", name, NUM2INT(RARRAY_AREF(loc, 1)));
1049 RB_GC_GUARD(loc);
1050
1051 len = (size_t)n;
1052 if (len >= sizeof(buf)) {
1053 buf[sizeof(buf)-2] = '*';
1054 buf[sizeof(buf)-1] = '\0';
1055 }
1056 SET_CURRENT_THREAD_NAME(buf);
1057 }
1058#endif
1059}
1060
1061static void
1062native_set_another_thread_name(rb_nativethread_id_t thread_id, VALUE name)
1063{
1064#if defined SET_ANOTHER_THREAD_NAME || defined SET_CURRENT_THREAD_NAME
1065 char buf[THREAD_NAME_MAX];
1066 const char *s = "";
1067# if !defined SET_ANOTHER_THREAD_NAME
1068 if (!pthread_equal(pthread_self(), thread_id)) return;
1069# endif
1070 if (!NIL_P(name)) {
1071 long n;
1072 RSTRING_GETMEM(name, s, n);
1073 if (n >= (int)sizeof(buf)) {
1074 memcpy(buf, s, sizeof(buf)-1);
1075 buf[sizeof(buf)-1] = '\0';
1076 s = buf;
1077 }
1078 }
1079# if defined SET_ANOTHER_THREAD_NAME
1080 SET_ANOTHER_THREAD_NAME(thread_id, s);
1081# elif defined SET_CURRENT_THREAD_NAME
1082 SET_CURRENT_THREAD_NAME(s);
1083# endif
1084#endif
1085}
1086
1087#if defined(RB_THREAD_T_HAS_NATIVE_ID) || defined(__APPLE__)
1088static VALUE
1089native_thread_native_thread_id(rb_thread_t *target_th)
1090{
1091 if (!target_th->nt) return Qnil;
1092
1093#ifdef RB_THREAD_T_HAS_NATIVE_ID
1094 int tid = target_th->nt->tid;
1095 if (tid == 0) return Qnil;
1096 return INT2FIX(tid);
1097#elif defined(__APPLE__)
1098 uint64_t tid;
1099/* The first condition is needed because MAC_OS_X_VERSION_10_6
1100 is not defined on 10.5, and while __POWERPC__ takes care of ppc/ppc64,
1101 i386 will be broken without this. Note, 10.5 is supported with GCC upstream,
1102 so it has C++17 and everything needed to build modern Ruby. */
1103# if (!defined(MAC_OS_X_VERSION_10_6) || \
1104 (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6) || \
1105 defined(__POWERPC__) /* never defined for PowerPC platforms */)
1106 const bool no_pthread_threadid_np = true;
1107# define NO_PTHREAD_MACH_THREAD_NP 1
1108# elif MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
1109 const bool no_pthread_threadid_np = false;
1110# else
1111# if !(defined(__has_attribute) && __has_attribute(availability))
1112 /* __API_AVAILABLE macro does nothing on gcc */
1113 __attribute__((weak)) int pthread_threadid_np(pthread_t, uint64_t*);
1114# endif
1115 /* Check weakly linked symbol */
1116 const bool no_pthread_threadid_np = !&pthread_threadid_np;
1117# endif
1118 if (no_pthread_threadid_np) {
1119 return ULL2NUM(pthread_mach_thread_np(pthread_self()));
1120 }
1121# ifndef NO_PTHREAD_MACH_THREAD_NP
1122 int e = pthread_threadid_np(target_th->nt->thread_id, &tid);
1123 if (e != 0) rb_syserr_fail(e, "pthread_threadid_np");
1124 return ULL2NUM((unsigned long long)tid);
1125# endif
1126#endif
1127}
1128# define USE_NATIVE_THREAD_NATIVE_THREAD_ID 1
1129#else
1130# define USE_NATIVE_THREAD_NATIVE_THREAD_ID 0
1131#endif
1132
1133static struct {
1134 rb_serial_t created_fork_gen;
1135 pthread_t pthread_id;
1136
1137 int comm_fds[2]; // r, w
1138
1139#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1140 int event_fd; // kernel event queue fd (epoll/kqueue)
1141#endif
1142#if HAVE_SYS_EPOLL_H && USE_MN_THREADS
1143#define EPOLL_EVENTS_MAX 0x10
1144 struct epoll_event finished_events[EPOLL_EVENTS_MAX];
1145#elif HAVE_SYS_EVENT_H && USE_MN_THREADS
1146#define KQUEUE_EVENTS_MAX 0x10
1147 struct kevent finished_events[KQUEUE_EVENTS_MAX];
1148#endif
1149
1150#if USE_MN_THREADS
1151 /* Timed waiters, bucketed by deadline into a hierarchical timer wheel;
1152 * untimed (fd-only) waiters keep a plain list. Both under waiting_lock.
1153 * The wheel operations all live in thread_sched_mn.c (timer_wheel_*). */
1154#define TIMER_WHEEL_LEVELS 4
1155#define TIMER_WHEEL_SLOT_BITS 6
1156#define TIMER_WHEEL_SLOTS (1 << TIMER_WHEEL_SLOT_BITS)
1157 struct timer_wheel_level {
1158 uint64_t occupied; // bit s: slots[s] is non-empty
1159 struct ccan_list_head slots[TIMER_WHEEL_SLOTS];
1160 } wheel[TIMER_WHEEL_LEVELS];
1161 uint64_t wheel_cursor_tick; // slots for ticks <= this are drained
1162 rb_hrtime_t next_expiry; // never later than the earliest deadline
1163 pthread_mutex_t waiting_lock; // the wheel and the flags of fd-less timed waits
1164
1165 /* The fd map entries and the flags of io waits are guarded per fd by a
1166 * shard lock, so unrelated fds register and wake in parallel. Whoever
1167 * clears an io wait's flags under its shard owns the wakeup. Lock order:
1168 * shard -> waiting_lock -> wake_pending_lock, never the other way. */
1169#define IO_WAIT_SHARDS 16
1170 pthread_mutex_t fd_shard_locks[IO_WAIT_SHARDS];
1171
1172 // signaled when wake_pending clears on a thread; see timer_thread_wake_fence
1173 pthread_mutex_t wake_pending_lock;
1174 rb_nativethread_cond_t wake_pending_cond;
1175#endif
1176
1177#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1178 // fd -> struct rb_fd_waiters, in chunks so entries never move. The chunk
1179 // table installs slots by CAS (chunks span shards); entry state is guarded
1180 // by the fd's shard lock.
1181#define FDMAP_MAX_CHUNKS 1024 // fds up to FDMAP_MAX_CHUNKS * FDMAP_CHUNK_SIZE
1182 struct rb_fd_waiters *fdmap_chunks[FDMAP_MAX_CHUNKS];
1183#endif
1184} timer_th = {
1185 .created_fork_gen = 0,
1186};
1187
1188#define TIMER_THREAD_CREATED_P() (timer_th.created_fork_gen == current_fork_gen)
1189
1190static void timer_thread_check_timeslice(rb_vm_t *vm);
1191static bool timeslice_scan(rb_vm_t *vm, bool interrupt);
1192static int timer_thread_set_timeout(rb_vm_t *vm);
1193
1194#include "thread_sched_mn.c"
1195
1196
1197void
1198rb_assert_sig(void)
1199{
1200 sigset_t oldmask;
1201 pthread_sigmask(0, NULL, &oldmask);
1202 if (sigismember(&oldmask, SIGVTALRM)) {
1203 rb_bug("!!!");
1204 }
1205 else {
1206 RUBY_DEBUG_LOG("ok");
1207 }
1208}
1209
1210
1211/* only use signal-safe system calls here */
1212static void
1213signal_communication_pipe(int fd)
1214{
1215#if USE_EVENTFD
1216 const uint64_t buff = 1;
1217#else
1218 const char buff = '!';
1219#endif
1220 ssize_t result;
1221
1222 /* already opened */
1223 if (fd >= 0) {
1224 retry:
1225 if ((result = write(fd, &buff, sizeof(buff))) <= 0) {
1226 int e = errno;
1227 switch (e) {
1228 case EINTR: goto retry;
1229 case EAGAIN:
1230#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1231 case EWOULDBLOCK:
1232#endif
1233 break;
1234 default:
1235 async_bug_fd("rb_thread_wakeup_timer_thread: write", e, fd);
1236 }
1237 }
1238 if (TT_DEBUG) WRITE_CONST(2, "rb_thread_wakeup_timer_thread: write\n");
1239 }
1240 else {
1241 // ignore wakeup
1242 }
1243}
1244
1245static void
1246timer_thread_wakeup_force(void)
1247{
1248 // should not use RUBY_DEBUG_LOG() because it can be called within signal handlers.
1249 signal_communication_pipe(timer_th.comm_fds[1]);
1250}
1251
1252
1253static void
1254rb_thread_create_timer_thread(void)
1255{
1256 rb_serial_t created_fork_gen = timer_th.created_fork_gen;
1257
1258 RUBY_DEBUG_LOG("fork_gen create:%d current:%d", (int)created_fork_gen, (int)current_fork_gen);
1259
1260 timer_th.created_fork_gen = current_fork_gen;
1261
1262 if (created_fork_gen != current_fork_gen) {
1263 if (created_fork_gen != 0) {
1264 RUBY_DEBUG_LOG("forked child process");
1265
1266 CLOSE_INVALIDATE_PAIR(timer_th.comm_fds);
1267#if USE_MN_THREADS
1268 // The parent's waiters do not exist in the child, and the armings
1269 // belong to the closed event backend: a stale entry would satisfy
1270 // fd_waiters_arm's want == armed_flags check and never arm the new
1271 // backend (a lost wake the old dynamic map also had).
1272 for (unsigned int ci = 0; ci < FDMAP_MAX_CHUNKS; ci++) {
1273 struct rb_fd_waiters *chunk = timer_th.fdmap_chunks[ci];
1274 if (chunk == NULL) continue;
1275 for (unsigned int i = 0; i < FDMAP_CHUNK_SIZE; i++) {
1276 ccan_list_head_init(&chunk[i].waiters);
1277 chunk[i].armed_flags = 0;
1278 chunk[i].generation++;
1279 }
1280 }
1281#endif
1282#if HAVE_SYS_EPOLL_H && USE_MN_THREADS
1283 close_invalidate(&timer_th.event_fd, "close event_fd");
1284#elif HAVE_SYS_EVENT_H && USE_MN_THREADS
1285 // A kqueue is not inherited across fork: the number names a closed
1286 // fd in the child, and closing it could hit a reused one.
1287 timer_th.event_fd = -1;
1288#endif
1289 // No mutex_destroy for waiting_lock: glibc returns EBUSY (and
1290 // rb_native_mutex_destroy rb_bugs) for a mutex another ractor's
1291 // M:N thread held at the fork moment. The initialize below
1292 // starts over.
1293 }
1294
1295#if USE_MN_THREADS
1296 for (int lvl = 0; lvl < TIMER_WHEEL_LEVELS; lvl++) {
1297 timer_th.wheel[lvl].occupied = 0;
1298 for (int slot = 0; slot < TIMER_WHEEL_SLOTS; slot++) {
1299 ccan_list_head_init(&timer_th.wheel[lvl].slots[slot]);
1300 }
1301 }
1302 timer_th.wheel_cursor_tick = timer_wheel_tick(rb_hrtime_now());
1303 timer_th.next_expiry = TIMER_WHEEL_NO_EXPIRY;
1304 rb_native_mutex_initialize(&timer_th.waiting_lock);
1305 for (int i = 0; i < IO_WAIT_SHARDS; i++) {
1306 rb_native_mutex_initialize(&timer_th.fd_shard_locks[i]);
1307 }
1308 rb_native_mutex_initialize(&timer_th.wake_pending_lock);
1309 rb_native_cond_initialize(&timer_th.wake_pending_cond);
1310#endif
1311
1312 // open communication channel
1313 setup_communication_pipe_internal(timer_th.comm_fds);
1314
1315 // open event fd
1316 timer_thread_setup_mn();
1317 }
1318
1319 int err = pthread_create(&timer_th.pthread_id, NULL, timer_thread_func, GET_VM());
1320 if (err != 0) {
1321 // The timer thread delivers signals and drives the M:N scheduler;
1322 // running without one only defers the failure to stranger places.
1323 rb_bug_errno("pthread_create (timer thread)", err);
1324 }
1325}
1326
1327static int
1328native_stop_timer_thread(void)
1329{
1330 RUBY_ATOMIC_SET(system_working, 0);
1331
1332 RUBY_DEBUG_LOG("wakeup send %d", timer_th.comm_fds[1]);
1333 timer_thread_wakeup_force();
1334 RUBY_DEBUG_LOG("wakeup sent");
1335 pthread_join(timer_th.pthread_id, NULL);
1336
1337 if (TT_DEBUG) fprintf(stderr, "stop timer thread\n");
1338
1339 return 1;
1340}
1341
1342static void
1343native_reset_timer_thread(void)
1344{
1345 //
1346}
1347
1348#ifdef HAVE_SIGALTSTACK
1349int
1350ruby_stack_overflowed_p(const rb_thread_t *th, const void *addr)
1351{
1352 void *base;
1353 size_t size;
1354 const size_t water_mark = RB_THREAD_PAGE_SIZE;
1355 STACK_GROW_DIR_DETECTION;
1356
1357 if (th) {
1358 size = th->ec->machine.stack_maxsize;
1359 base = (char *)th->ec->machine.stack_start - STACK_DIR_UPPER(0, size);
1360 }
1361#ifdef STACKADDR_AVAILABLE
1362 else if (get_stack(&base, &size) == 0) {
1363# ifdef __APPLE__
1364 // th is NULL in this branch; ask about the calling thread itself.
1365 if (pthread_equal(pthread_self(), native_main_thread.id)) {
1366 struct rlimit rlim;
1367 if (getrlimit(RLIMIT_STACK, &rlim) == 0 && rlim.rlim_cur > size) {
1368 size = (size_t)rlim.rlim_cur;
1369 }
1370 }
1371# endif
1372 base = (char *)base + STACK_DIR_UPPER(+size, -size);
1373 }
1374#endif
1375 else {
1376 return 0;
1377 }
1378
1379 if (size > water_mark) size = water_mark;
1380 if (IS_STACK_DIR_UPPER()) {
1381 if (size > ~(size_t)base+1) size = ~(size_t)base+1;
1382 if (addr > base && addr <= (void *)((char *)base + size)) return 1;
1383 }
1384 else {
1385 if (size > (size_t)base) size = (size_t)base;
1386 if (addr > (void *)((char *)base - size) && addr <= base) return 1;
1387 }
1388 return 0;
1389}
1390#endif
1391
1392int
1393rb_reserved_fd_p(int fd)
1394{
1395 /* no false-positive if out-of-FD at startup */
1396 if (fd < 0) return 0;
1397
1398 if (fd == timer_th.comm_fds[0] ||
1399 fd == timer_th.comm_fds[1]
1400#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1401 || fd == timer_th.event_fd
1402#endif
1403 ) {
1404 goto check_fork_gen;
1405 }
1406 return 0;
1407
1408 check_fork_gen:
1409 if (timer_th.created_fork_gen == current_fork_gen) {
1410 /* async-signal-safe */
1411 return 1;
1412 }
1413 else {
1414 return 0;
1415 }
1416}
1417
1418rb_nativethread_id_t
1420{
1421 return pthread_self();
1422}
1423
1424#if defined(USE_POLL) && !defined(HAVE_PPOLL)
1425/* TODO: don't ignore sigmask */
1426static int
1427ruby_ppoll(struct pollfd *fds, nfds_t nfds,
1428 const struct timespec *ts, const sigset_t *sigmask)
1429{
1430 int timeout_ms;
1431
1432 if (ts) {
1433 int tmp, tmp2;
1434
1435 if (ts->tv_sec > INT_MAX/1000)
1436 timeout_ms = INT_MAX;
1437 else {
1438 tmp = (int)(ts->tv_sec * 1000);
1439 /* round up 1ns to 1ms to avoid excessive wakeups for <1ms sleep */
1440 tmp2 = (int)((ts->tv_nsec + 999999L) / (1000L * 1000L));
1441 if (INT_MAX - tmp < tmp2)
1442 timeout_ms = INT_MAX;
1443 else
1444 timeout_ms = (int)(tmp + tmp2);
1445 }
1446 }
1447 else
1448 timeout_ms = -1;
1449
1450 return poll(fds, nfds, timeout_ms);
1451}
1452# define ppoll(fds,nfds,ts,sigmask) ruby_ppoll((fds),(nfds),(ts),(sigmask))
1453#endif
1454
1455
1456// fork read-write lock (only for pthread)
1457static pthread_rwlock_t rb_thread_fork_rw_lock = PTHREAD_RWLOCK_INITIALIZER;
1458
1459void
1460rb_thread_release_fork_lock(void)
1461{
1462 int r;
1463 if ((r = pthread_rwlock_unlock(&rb_thread_fork_rw_lock))) {
1464 rb_bug_errno("pthread_rwlock_unlock", r);
1465 }
1466}
1467
1468void
1469rb_thread_reset_fork_lock(void)
1470{
1471 int r;
1472 if ((r = pthread_rwlock_destroy(&rb_thread_fork_rw_lock))) {
1473 rb_bug_errno("pthread_rwlock_destroy", r);
1474 }
1475
1476 if ((r = pthread_rwlock_init(&rb_thread_fork_rw_lock, NULL))) {
1477 rb_bug_errno("pthread_rwlock_init", r);
1478 }
1479}
1480
1481void *
1482rb_thread_prevent_fork(void *(*func)(void *), void *data)
1483{
1484 int r;
1485 if ((r = pthread_rwlock_rdlock(&rb_thread_fork_rw_lock))) {
1486 rb_bug_errno("pthread_rwlock_rdlock", r);
1487 }
1488 void *result = func(data);
1489 rb_thread_release_fork_lock();
1490 return result;
1491}
1492
1493void
1494rb_thread_acquire_fork_lock(void)
1495{
1496 int r;
1497 if ((r = pthread_rwlock_wrlock(&rb_thread_fork_rw_lock))) {
1498 rb_bug_errno("pthread_rwlock_wrlock", r);
1499 }
1500}
1501
1502// thread internal event hooks (only for pthread)
1503
1504struct rb_internal_thread_event_hook {
1505 rb_internal_thread_event_callback callback;
1506 rb_event_flag_t event;
1507 void *user_data;
1508
1509 struct rb_internal_thread_event_hook *next;
1510};
1511
1512static pthread_rwlock_t rb_internal_thread_event_hooks_rw_lock = PTHREAD_RWLOCK_INITIALIZER;
1513
1514/* For the GC: whether any thread-event hook is registered right now. The rwlock
1515 * makes the answer happen-after any completed registration; a hook registered
1516 * after this read gets no event from the asking thread (rb_thread_execute_hooks
1517 * skips a swept thread), so it never sees the objects the caller may collect. */
1518bool
1519rb_thread_event_hooks_registered_p(void)
1520{
1521 int r;
1522 if ((r = pthread_rwlock_rdlock(&rb_internal_thread_event_hooks_rw_lock))) {
1523 rb_bug_errno("pthread_rwlock_rdlock", r);
1524 }
1525 const bool registered = (rb_internal_thread_event_hooks != NULL);
1526 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1527 rb_bug_errno("pthread_rwlock_unlock", r);
1528 }
1529 return registered;
1530}
1531
1532#if defined(HAVE_WORKING_FORK)
1533static void
1534rb_internal_thread_event_hooks_rw_lock_atfork(void)
1535{
1536 // After fork(), this rwlock may have been held by a now-dead thread.
1537 //
1538 // pthread_rwlock_destroy() on a held lock is undefined behavior, and
1539 // pthread_rwlock_init() on an already-initialized lock is also undefined
1540 // behavior
1541 //
1542 // Direct assignment of PTHREAD_RWLOCK_INITIALIZER is safe and portable.
1543 rb_internal_thread_event_hooks_rw_lock =
1544 (pthread_rwlock_t)PTHREAD_RWLOCK_INITIALIZER;
1545}
1546#endif
1547
1548rb_internal_thread_event_hook_t *
1549rb_internal_thread_add_event_hook(rb_internal_thread_event_callback callback, rb_event_flag_t internal_event, void *user_data)
1550{
1551 rb_internal_thread_event_hook_t *hook = ALLOC_N(rb_internal_thread_event_hook_t, 1);
1552 hook->callback = callback;
1553 hook->user_data = user_data;
1554 hook->event = internal_event;
1555
1556 int r;
1557 if ((r = pthread_rwlock_wrlock(&rb_internal_thread_event_hooks_rw_lock))) {
1558 rb_bug_errno("pthread_rwlock_wrlock", r);
1559 }
1560
1561 hook->next = rb_internal_thread_event_hooks;
1562 ATOMIC_PTR_EXCHANGE(rb_internal_thread_event_hooks, hook);
1563
1564 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1565 rb_bug_errno("pthread_rwlock_unlock", r);
1566 }
1567 return hook;
1568}
1569
1570bool
1571rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t * hook)
1572{
1573 int r;
1574 if ((r = pthread_rwlock_wrlock(&rb_internal_thread_event_hooks_rw_lock))) {
1575 rb_bug_errno("pthread_rwlock_wrlock", r);
1576 }
1577
1578 bool success = FALSE;
1579
1580 if (rb_internal_thread_event_hooks == hook) {
1581 ATOMIC_PTR_EXCHANGE(rb_internal_thread_event_hooks, hook->next);
1582 success = TRUE;
1583 }
1584 else {
1585 rb_internal_thread_event_hook_t *h = rb_internal_thread_event_hooks;
1586
1587 do {
1588 if (h->next == hook) {
1589 h->next = hook->next;
1590 success = TRUE;
1591 break;
1592 }
1593 } while ((h = h->next));
1594 }
1595
1596 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1597 rb_bug_errno("pthread_rwlock_unlock", r);
1598 }
1599
1600 if (success) {
1601 SIZED_FREE(hook);
1602 }
1603 return success;
1604}
1605
1606static void
1607rb_thread_execute_hooks(rb_event_flag_t event, rb_thread_t *th)
1608{
1609 int r;
1610
1611 /* th->self == 0: the dying thread's final collection swept its Thread wrapper, so
1612 * no hook existed then; one registered since has no ordering claim to this event. */
1613 if (th->self == 0) return;
1614 if ((r = pthread_rwlock_rdlock(&rb_internal_thread_event_hooks_rw_lock))) {
1615 rb_bug_errno("pthread_rwlock_rdlock", r);
1616 }
1617
1618 if (rb_internal_thread_event_hooks) {
1619 rb_internal_thread_event_hook_t *h = rb_internal_thread_event_hooks;
1620 do {
1621 if (h->event & event) {
1622 rb_internal_thread_event_data_t event_data = {
1623 .thread = th->self,
1624 };
1625 (*h->callback)(event, &event_data, h->user_data);
1626 }
1627 } while((h = h->next));
1628 }
1629 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1630 rb_bug_errno("pthread_rwlock_unlock", r);
1631 }
1632}
1633
1634#endif /* THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION */
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition atomic.h:118
#define RUBY_ATOMIC_LOAD(var)
Atomic load.
Definition atomic.h:175
#define RUBY_ATOMIC_SET(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except for the return type.
Definition atomic.h:185
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define NIL_P
Old name of RB_NIL_P.
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1441
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:4042
void rb_bug_errno(const char *mesg, int errno_arg)
This is a wrapper of rb_bug() which automatically constructs appropriate message from the passed errn...
Definition error.c:1151
int rb_cloexec_pipe(int fildes[2])
Opens a pipe with closing on exec.
Definition io.c:429
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:250
int rb_reserved_fd_p(int fd)
Queries if the given FD is reserved or not.
void rb_timespec_now(struct timespec *ts)
Fills the current time into the given struct.
Definition time.c:2021
int len
Length of the buffer.
Definition io.h:8
#define RUBY_INTERNAL_THREAD_EVENT_RESUMED
Triggered when a thread successfully acquired the GVL.
Definition thread.h:249
rb_internal_thread_event_hook_t * rb_internal_thread_add_event_hook(rb_internal_thread_event_callback func, rb_event_flag_t events, void *data)
Registers a thread event hook function.
#define RUBY_INTERNAL_THREAD_EVENT_EXITED
Triggered when a thread exits.
Definition thread.h:263
#define RUBY_INTERNAL_THREAD_EVENT_SUSPENDED
Triggered when a thread released the GVL.
Definition thread.h:256
#define RUBY_INTERNAL_THREAD_EVENT_STARTED
Triggered when a new thread is started.
Definition thread.h:235
bool rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t *hook)
Unregister the passed hook.
#define RUBY_INTERNAL_THREAD_EVENT_READY
Triggered when a thread attempt to acquire the GVL.
Definition thread.h:242
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define rb_fd_select
Waits for multiple file descriptors at once.
Definition posix.h:66
#define RARRAY_AREF(a, i)
Definition rarray.h:402
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
The data structure which wraps the fd_set bitmap used by select(2).
Definition largesize.h:71
rb_nativethread_id_t rb_nativethread_self(void)
Queries the ID of the native thread that is calling this function.
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_cond_initialize(rb_nativethread_cond_t *cond)
Fills the passed condition variable with an initial value.
int rb_native_mutex_trylock(rb_nativethread_lock_t *lock)
Identical to rb_native_mutex_lock(), except it doesn't block in case rb_native_mutex_lock() would.
void rb_native_cond_broadcast(rb_nativethread_cond_t *cond)
Signals a condition variable.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_native_cond_destroy(rb_nativethread_cond_t *cond)
Destroys the passed condition variable.
void rb_native_cond_signal(rb_nativethread_cond_t *cond)
Signals a condition variable.
void rb_native_cond_wait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex)
Waits for the passed condition variable to be signalled.
void rb_native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, unsigned long msec)
Identical to rb_native_cond_wait(), except it additionally takes timeout in msec resolution.
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40