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