Ruby 4.1.0dev (2026-09-12 revision d5793e0b62b17dd182e69b28e4aaa008e821b8ab)
thread_pthread.c (d5793e0b62b17dd182e69b28e4aaa008e821b8ab)
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// Whether the calling native thread may leave the shared pool. The process's
641// main pthread cannot: under RUBY_MN_THREADS=2 its loop runs on a stack only
642// it could free (thread_sched_main_to_shared). By pthread_self(), not
643// nt->thread_id, which pthread_create may still be writing.
644static bool
645native_thread_self_can_retire_p(void)
646{
647 return !pthread_equal(pthread_self(), native_main_thread.id);
648}
649
650#if defined(HAVE_WORKING_FORK)
651// The forking thread's pthread is the child's only one, hence its main one
652static void
653native_main_thread_atfork(void)
654{
655 native_main_thread.id = pthread_self();
656 // The stack recorded here is the parent's initial one; this thread's is
657 // another. Nothing reads it for a thread that is already running, and
658 // saying "unknown" beats saying the wrong bounds.
659 native_main_thread.stack_maxsize = 0;
660}
661#endif
662
663#ifdef STACK_END_ADDRESS
664extern void *STACK_END_ADDRESS;
665#endif
666
667static void
668native_thread_init_main_thread_stack(void *addr)
669{
670 native_main_thread.id = pthread_self();
671#ifdef RUBY_ASAN_ENABLED
672 addr = asan_get_real_stack_addr((void *)addr);
673#endif
674
675#if MAINSTACKADDR_AVAILABLE
676 if (native_main_thread.stack_maxsize) return;
677 {
678 void* stackaddr;
679 size_t size;
680 if (get_main_stack(&stackaddr, &size) == 0) {
681 native_main_thread.stack_maxsize = size;
682 native_main_thread.stack_start = stackaddr;
683 goto bound_check;
684 }
685 }
686#endif
687#ifdef STACK_END_ADDRESS
688 native_main_thread.stack_start = STACK_END_ADDRESS;
689#else
690 if (!native_main_thread.stack_start ||
691 STACK_UPPER((VALUE *)(void *)&addr,
692 native_main_thread.stack_start > (VALUE *)addr,
693 native_main_thread.stack_start < (VALUE *)addr)) {
694 native_main_thread.stack_start = (VALUE *)addr;
695 }
696#endif
697 {
698#if defined(HAVE_GETRLIMIT)
699#if defined(PTHREAD_STACK_DEFAULT)
700 size_t size = PTHREAD_STACK_DEFAULT;
701#else
702 size_t size = RUBY_VM_THREAD_VM_STACK_SIZE;
703#endif
704 size_t space;
705 struct rlimit rlim;
706 STACK_GROW_DIR_DETECTION;
707 if (getrlimit(RLIMIT_STACK, &rlim) == 0) {
708 size = (size_t)rlim.rlim_cur;
709 }
710 addr = native_main_thread.stack_start;
711 if (IS_STACK_DIR_UPPER()) {
712 space = ((size_t)((char *)addr + size) / RB_THREAD_PAGE_SIZE) * RB_THREAD_PAGE_SIZE - (size_t)addr;
713 }
714 else {
715 space = (size_t)addr - ((size_t)((char *)addr - size) / RB_THREAD_PAGE_SIZE + 1) * RB_THREAD_PAGE_SIZE;
716 }
717 native_main_thread.stack_maxsize = space;
718#endif
719 }
720
721#if MAINSTACKADDR_AVAILABLE
722 bound_check:
723#endif
724 /* If addr is out of range of main-thread stack range estimation, */
725 /* it should be on co-routine (alternative stack). [Feature #2294] */
726 {
727 void *start, *end;
728 STACK_GROW_DIR_DETECTION;
729
730 if (IS_STACK_DIR_UPPER()) {
731 start = native_main_thread.stack_start;
732 end = (char *)native_main_thread.stack_start + native_main_thread.stack_maxsize;
733 }
734 else {
735 start = (char *)native_main_thread.stack_start - native_main_thread.stack_maxsize;
736 end = native_main_thread.stack_start;
737 }
738
739 if ((void *)addr < start || (void *)addr > end) {
740 /* out of range */
741 native_main_thread.stack_start = (VALUE *)addr;
742 native_main_thread.stack_maxsize = 0; /* unknown */
743 }
744 }
745}
746
747#define CHECK_ERR(expr) \
748 {int err = (expr); if (err) {rb_bug_errno(#expr, err);}}
749
750static int
751native_thread_init_stack(rb_thread_t *th, void *local_in_parent_frame)
752{
753 rb_nativethread_id_t curr = pthread_self();
754#ifdef RUBY_ASAN_ENABLED
755 local_in_parent_frame = asan_get_real_stack_addr(local_in_parent_frame);
756 th->ec->machine.asan_fake_stack_handle = asan_get_thread_fake_stack_handle();
757#endif
758
759 if (!native_main_thread.id) {
760 /* This thread is the first thread, must be the main thread -
761 * configure the native_main_thread object */
762 native_thread_init_main_thread_stack(local_in_parent_frame);
763 }
764
765 if (th->sched.context != NULL) {
766 // an M:N thread runs on the pool stack native_thread_create_shared
767 // recorded, whichever native thread (the main one included) hosts it.
768 // Not by nt->dedicated: a RESUMED hook may have pinned the nt already.
769 }
770 else if (pthread_equal(curr, native_main_thread.id)) {
771 th->ec->machine.stack_start = native_main_thread.stack_start;
772 th->ec->machine.stack_maxsize = native_main_thread.stack_maxsize;
773 }
774 else {
775#ifdef STACKADDR_AVAILABLE
776 void *start;
777 size_t size;
778
779 if (get_stack(&start, &size) == 0) {
780 uintptr_t diff = (uintptr_t)start - (uintptr_t)local_in_parent_frame;
781 th->ec->machine.stack_start = local_in_parent_frame;
782 th->ec->machine.stack_maxsize = size - diff;
783 }
784#else
785 rb_raise(rb_eNotImpError, "ruby engine can initialize only in the main thread");
786#endif
787 }
788
789 return 0;
790}
791
792struct nt_param {
793 rb_vm_t *vm;
794 struct rb_native_thread *nt;
795};
796
797
798static int
799native_thread_create0(struct rb_native_thread *nt)
800{
801 int err = 0;
802 pthread_attr_t attr;
803
804 const size_t stack_size = nt->vm->default_params.thread_machine_stack_size;
805
806#ifdef USE_SIGALTSTACK
807 nt->altstack = rb_allocate_sigaltstack();
808#endif
809
810 CHECK_ERR(pthread_attr_init(&attr));
811
812# ifdef PTHREAD_STACK_MIN
813 RUBY_DEBUG_LOG("stack size: %lu", (unsigned long)stack_size);
814 CHECK_ERR(pthread_attr_setstacksize(&attr, stack_size));
815# endif
816
817# ifdef HAVE_PTHREAD_ATTR_SETINHERITSCHED
818 CHECK_ERR(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
819# endif
820 CHECK_ERR(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
821
822 err = pthread_create(&nt->thread_id, &attr, nt_start, nt);
823
824 RUBY_DEBUG_LOG("nt:%d err:%d", (int)nt->serial, err);
825
826 CHECK_ERR(pthread_attr_destroy(&attr));
827
828 return err;
829}
830
831static void
832native_thread_setup(struct rb_native_thread *nt)
833{
834 // init cond
835 rb_native_cond_initialize(&nt->readyq);
836 // also for the main thread's nt: a zero-filled mutex is not usable on macOS
837 rb_native_mutex_initialize(&nt->running_th_lock);
838}
839
840static void
841native_thread_setup_on_thread(struct rb_native_thread *nt)
842{
843 // init tid
844#ifdef RB_THREAD_T_HAS_NATIVE_ID
845 nt->tid = get_native_thread_id();
846#endif
847
848 // init signal handler
849 RB_ALTSTACK_INIT(nt->altstack, nt->altstack);
850}
851
852static struct rb_native_thread *
853native_thread_alloc(void)
854{
855 struct rb_native_thread *nt = ZALLOC(struct rb_native_thread);
856 native_thread_setup(nt);
857
858#if USE_MN_THREADS
859 nt->nt_context = ruby_xmalloc(sizeof(struct coroutine_context));
860#endif
861
862#if USE_RUBY_DEBUG_LOG
863 static rb_atomic_t nt_serial = 2;
864 nt->serial = RUBY_ATOMIC_FETCH_ADD(nt_serial, 1);
865#endif
866 return nt;
867}
868
869
870
871
872#if USE_NATIVE_THREAD_PRIORITY
873
874static void
875native_thread_apply_priority(rb_thread_t *th)
876{
877#if defined(_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING > 0)
878 struct sched_param sp;
879 int policy;
880 int priority = 0 - th->priority;
881 int max, min;
882 pthread_getschedparam(th->nt->thread_id, &policy, &sp);
883 max = sched_get_priority_max(policy);
884 min = sched_get_priority_min(policy);
885
886 if (min > priority) {
887 priority = min;
888 }
889 else if (max < priority) {
890 priority = max;
891 }
892
893 sp.sched_priority = priority;
894 pthread_setschedparam(th->nt->thread_id, policy, &sp);
895#else
896 /* not touched */
897#endif
898}
899
900#endif /* USE_NATIVE_THREAD_PRIORITY */
901
902static int
903native_fd_select(int n, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout, rb_thread_t *th)
904{
905 return rb_fd_select(n, readfds, writefds, exceptfds, timeout);
906}
907
908/*
909 * Send a signal to make the target thread return from a blocking syscall.
910 * Maybe any signal is ok, but we chose SIGVTALRM (see null_func).
911 */
912static void
913native_thread_interrupt(rb_thread_t *th)
914{
915 pthread_kill(th->nt->thread_id, SIGVTALRM);
916}
917
918static int
919native_thread_default_max_cpu(void)
920{
921#if defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
922 long nprocessors = sysconf(_SC_NPROCESSORS_ONLN);
923 return (nprocessors > 0) ? (int)nprocessors : 8;
924#else
925 return 8;
926#endif
927}
928
929
930#define TT_DEBUG 0
931#define WRITE_CONST(fd, str) (void)(write((fd),(str),sizeof(str)-1)<0)
932
933void
934rb_thread_wakeup_timer_thread(int sig)
935{
936 // This function can be called from signal handlers so that
937 // pthread_mutex_lock() should not be used.
938
939 // wakeup timer thread
940 timer_thread_wakeup_force();
941
942 // interrupt main thread if main thread is available
943 if (RUBY_ATOMIC_LOAD(system_working)) {
944 rb_vm_t *vm = GET_VM();
945 rb_thread_t *main_th = vm->ractor.main_thread;
946
947 if (main_th) {
948 volatile rb_execution_context_t *main_th_ec = ACCESS_ONCE(rb_execution_context_t *, main_th->ec);
949
950 if (main_th_ec) {
951 RUBY_VM_SET_TRAP_INTERRUPT(main_th_ec);
952
953 if (vm->ubf_async_safe && main_th->unblock.func) {
954 (main_th->unblock.func)(main_th->unblock.arg);
955 }
956 }
957 }
958 }
959}
960
961#define CLOSE_INVALIDATE_PAIR(expr) \
962 close_invalidate_pair(expr,"close_invalidate: "#expr)
963static void
964close_invalidate(int *fdp, const char *msg)
965{
966 int fd = *fdp;
967
968 *fdp = -1;
969 if (close(fd) < 0) {
970 async_bug_fd(msg, errno, fd);
971 }
972}
973
974static void
975close_invalidate_pair(int fds[2], const char *msg)
976{
977 if (USE_EVENTFD && fds[0] == fds[1]) {
978 fds[1] = -1; // disable write port first
979 close_invalidate(&fds[0], msg);
980 }
981 else {
982 close_invalidate(&fds[1], msg);
983 close_invalidate(&fds[0], msg);
984 }
985}
986
987static void
988set_nonblock(int fd)
989{
990 int oflags;
991 int err;
992
993 oflags = fcntl(fd, F_GETFL);
994 if (oflags == -1)
995 rb_sys_fail(0);
996 oflags |= O_NONBLOCK;
997 err = fcntl(fd, F_SETFL, oflags);
998 if (err == -1)
999 rb_sys_fail(0);
1000}
1001
1002/* communication pipe with timer thread and signal handler */
1003static void
1004setup_communication_pipe_internal(int pipes[2])
1005{
1006 int err;
1007
1008 if (pipes[0] > 0 || pipes[1] > 0) {
1009 VM_ASSERT(pipes[0] > 0);
1010 VM_ASSERT(pipes[1] > 0);
1011 return;
1012 }
1013
1014 /*
1015 * Don't bother with eventfd on ancient Linux 2.6.22..2.6.26 which were
1016 * missing EFD_* flags, they can fall back to pipe
1017 */
1018#if USE_EVENTFD && defined(EFD_NONBLOCK) && defined(EFD_CLOEXEC)
1019 pipes[0] = pipes[1] = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);
1020
1021 if (pipes[0] >= 0) {
1022 rb_update_max_fd(pipes[0]);
1023 return;
1024 }
1025#endif
1026
1027 err = rb_cloexec_pipe(pipes);
1028 if (err != 0) {
1029 rb_bug("can not create communication pipe");
1030 }
1031 rb_update_max_fd(pipes[0]);
1032 rb_update_max_fd(pipes[1]);
1033 set_nonblock(pipes[0]);
1034 set_nonblock(pipes[1]);
1035}
1036
1037#if !defined(SET_CURRENT_THREAD_NAME) && defined(__linux__) && defined(PR_SET_NAME)
1038# define SET_CURRENT_THREAD_NAME(name) prctl(PR_SET_NAME, name)
1039#endif
1040
1041enum {
1042 THREAD_NAME_MAX =
1043#if defined(__linux__)
1044 16
1045#elif defined(__APPLE__)
1046/* Undocumented, and main thread seems unlimited */
1047 64
1048#else
1049 16
1050#endif
1051};
1052
1053static VALUE threadptr_invoke_proc_location(rb_thread_t *th);
1054
1055static void
1056native_set_thread_name(rb_thread_t *th)
1057{
1058#ifdef SET_CURRENT_THREAD_NAME
1059 VALUE loc;
1060
1061 // An M:N thread does not own the native thread it runs on: naming it here
1062 // would name whichever nt started it (under RUBY_MN_THREADS=2 that can be
1063 // the process's main one, whose name is the process's). Thread#name= is
1064 // skipped for the same reason (rb_thread_setname).
1065 if (!th->has_dedicated_nt) return;
1066
1067 if (!NIL_P(loc = th->name)) {
1068 SET_CURRENT_THREAD_NAME(RSTRING_PTR(loc));
1069 }
1070 else if ((loc = threadptr_invoke_proc_location(th)) != Qnil) {
1071 char *name, *p;
1072 char buf[THREAD_NAME_MAX];
1073 size_t len;
1074 int n;
1075
1076 name = RSTRING_PTR(RARRAY_AREF(loc, 0));
1077 p = strrchr(name, '/'); /* show only the basename of the path. */
1078 if (p && p[1])
1079 name = p + 1;
1080
1081 n = snprintf(buf, sizeof(buf), "%s:%d", name, NUM2INT(RARRAY_AREF(loc, 1)));
1082 RB_GC_GUARD(loc);
1083
1084 len = (size_t)n;
1085 if (len >= sizeof(buf)) {
1086 buf[sizeof(buf)-2] = '*';
1087 buf[sizeof(buf)-1] = '\0';
1088 }
1089 SET_CURRENT_THREAD_NAME(buf);
1090 }
1091#endif
1092}
1093
1094static void
1095native_set_another_thread_name(rb_nativethread_id_t thread_id, VALUE name)
1096{
1097#if defined SET_ANOTHER_THREAD_NAME || defined SET_CURRENT_THREAD_NAME
1098 char buf[THREAD_NAME_MAX];
1099 const char *s = "";
1100# if !defined SET_ANOTHER_THREAD_NAME
1101 if (!pthread_equal(pthread_self(), thread_id)) return;
1102# endif
1103 if (!NIL_P(name)) {
1104 long n;
1105 RSTRING_GETMEM(name, s, n);
1106 if (n >= (int)sizeof(buf)) {
1107 memcpy(buf, s, sizeof(buf)-1);
1108 buf[sizeof(buf)-1] = '\0';
1109 s = buf;
1110 }
1111 }
1112# if defined SET_ANOTHER_THREAD_NAME
1113 SET_ANOTHER_THREAD_NAME(thread_id, s);
1114# elif defined SET_CURRENT_THREAD_NAME
1115 SET_CURRENT_THREAD_NAME(s);
1116# endif
1117#endif
1118}
1119
1120#if defined(RB_THREAD_T_HAS_NATIVE_ID) || defined(__APPLE__)
1121static VALUE
1122native_thread_native_thread_id(rb_thread_t *target_th)
1123{
1124 if (!target_th->nt) return Qnil;
1125
1126#ifdef RB_THREAD_T_HAS_NATIVE_ID
1127 int tid = target_th->nt->tid;
1128 if (tid == 0) return Qnil;
1129 return INT2FIX(tid);
1130#elif defined(__APPLE__)
1131 uint64_t tid;
1132/* The first condition is needed because MAC_OS_X_VERSION_10_6
1133 is not defined on 10.5, and while __POWERPC__ takes care of ppc/ppc64,
1134 i386 will be broken without this. Note, 10.5 is supported with GCC upstream,
1135 so it has C++17 and everything needed to build modern Ruby. */
1136# if (!defined(MAC_OS_X_VERSION_10_6) || \
1137 (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6) || \
1138 defined(__POWERPC__) /* never defined for PowerPC platforms */)
1139 const bool no_pthread_threadid_np = true;
1140# define NO_PTHREAD_MACH_THREAD_NP 1
1141# elif MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
1142 const bool no_pthread_threadid_np = false;
1143# else
1144# if !(defined(__has_attribute) && __has_attribute(availability))
1145 /* __API_AVAILABLE macro does nothing on gcc */
1146 __attribute__((weak)) int pthread_threadid_np(pthread_t, uint64_t*);
1147# endif
1148 /* Check weakly linked symbol */
1149 const bool no_pthread_threadid_np = !&pthread_threadid_np;
1150# endif
1151 if (no_pthread_threadid_np) {
1152 return ULL2NUM(pthread_mach_thread_np(pthread_self()));
1153 }
1154# ifndef NO_PTHREAD_MACH_THREAD_NP
1155 int e = pthread_threadid_np(target_th->nt->thread_id, &tid);
1156 if (e != 0) rb_syserr_fail(e, "pthread_threadid_np");
1157 return ULL2NUM((unsigned long long)tid);
1158# endif
1159#endif
1160}
1161# define USE_NATIVE_THREAD_NATIVE_THREAD_ID 1
1162#else
1163# define USE_NATIVE_THREAD_NATIVE_THREAD_ID 0
1164#endif
1165
1166static struct {
1167 rb_serial_t created_fork_gen;
1168 pthread_t pthread_id;
1169
1170 int comm_fds[2]; // r, w
1171
1172#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1173 int event_fd; // kernel event queue fd (epoll/kqueue)
1174#endif
1175#if HAVE_SYS_EPOLL_H && USE_MN_THREADS
1176#define EPOLL_EVENTS_MAX 0x10
1177 struct epoll_event finished_events[EPOLL_EVENTS_MAX];
1178#elif HAVE_SYS_EVENT_H && USE_MN_THREADS
1179#define KQUEUE_EVENTS_MAX 0x10
1180 struct kevent finished_events[KQUEUE_EVENTS_MAX];
1181#endif
1182
1183#if USE_MN_THREADS
1184 /* Timed waiters, bucketed by deadline into a hierarchical timer wheel;
1185 * untimed (fd-only) waiters keep a plain list. Both under waiting_lock.
1186 * The wheel operations all live in thread_sched_mn.c (timer_wheel_*). */
1187#define TIMER_WHEEL_LEVELS 4
1188#define TIMER_WHEEL_SLOT_BITS 6
1189#define TIMER_WHEEL_SLOTS (1 << TIMER_WHEEL_SLOT_BITS)
1190 struct timer_wheel_level {
1191 uint64_t occupied; // bit s: slots[s] is non-empty
1192 struct ccan_list_head slots[TIMER_WHEEL_SLOTS];
1193 } wheel[TIMER_WHEEL_LEVELS];
1194 uint64_t wheel_cursor_tick; // slots for ticks <= this are drained
1195 rb_hrtime_t next_expiry; // never later than the earliest deadline
1196 pthread_mutex_t waiting_lock; // the wheel and the flags of fd-less timed waits
1197
1198 /* The fd map entries and the flags of io waits are guarded per fd by a
1199 * shard lock, so unrelated fds register and wake in parallel. Whoever
1200 * clears an io wait's flags under its shard owns the wakeup. Lock order:
1201 * shard -> waiting_lock -> wake_pending_lock, never the other way. */
1202#define IO_WAIT_SHARDS 16
1203 pthread_mutex_t fd_shard_locks[IO_WAIT_SHARDS];
1204
1205 // signaled when wake_pending clears on a thread; see timer_thread_wake_fence
1206 pthread_mutex_t wake_pending_lock;
1207 rb_nativethread_cond_t wake_pending_cond;
1208#endif
1209
1210#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1211 // fd -> struct rb_fd_waiters, in chunks so entries never move. The chunk
1212 // table installs slots by CAS (chunks span shards); entry state is guarded
1213 // by the fd's shard lock.
1214#define FDMAP_MAX_CHUNKS 1024 // fds up to FDMAP_MAX_CHUNKS * FDMAP_CHUNK_SIZE
1215 struct rb_fd_waiters *fdmap_chunks[FDMAP_MAX_CHUNKS];
1216#endif
1217} timer_th = {
1218 .created_fork_gen = 0,
1219};
1220
1221#define TIMER_THREAD_CREATED_P() (timer_th.created_fork_gen == current_fork_gen)
1222
1223static void timer_thread_check_timeslice(rb_vm_t *vm);
1224static bool timeslice_scan(rb_vm_t *vm, bool interrupt);
1225static int timer_thread_set_timeout(rb_vm_t *vm);
1226
1227#include "thread_sched_mn.c"
1228
1229/* only use signal-safe system calls here */
1230static void
1231signal_communication_pipe(int fd)
1232{
1233#if USE_EVENTFD
1234 const uint64_t buff = 1;
1235#else
1236 const char buff = '!';
1237#endif
1238 ssize_t result;
1239
1240 /* already opened */
1241 if (fd >= 0) {
1242 retry:
1243 if ((result = write(fd, &buff, sizeof(buff))) <= 0) {
1244 int e = errno;
1245 switch (e) {
1246 case EINTR: goto retry;
1247 case EAGAIN:
1248#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1249 case EWOULDBLOCK:
1250#endif
1251 break;
1252 default:
1253 async_bug_fd("rb_thread_wakeup_timer_thread: write", e, fd);
1254 }
1255 }
1256 if (TT_DEBUG) WRITE_CONST(2, "rb_thread_wakeup_timer_thread: write\n");
1257 }
1258 else {
1259 // ignore wakeup
1260 }
1261}
1262
1263static void
1264timer_thread_wakeup_force(void)
1265{
1266 // should not use RUBY_DEBUG_LOG() because it can be called within signal handlers.
1267 signal_communication_pipe(timer_th.comm_fds[1]);
1268}
1269
1270
1271static void
1272rb_thread_create_timer_thread(void)
1273{
1274 rb_serial_t created_fork_gen = timer_th.created_fork_gen;
1275
1276 RUBY_DEBUG_LOG("fork_gen create:%d current:%d", (int)created_fork_gen, (int)current_fork_gen);
1277
1278 timer_th.created_fork_gen = current_fork_gen;
1279
1280 if (created_fork_gen != current_fork_gen) {
1281 if (created_fork_gen != 0) {
1282 RUBY_DEBUG_LOG("forked child process");
1283
1284 CLOSE_INVALIDATE_PAIR(timer_th.comm_fds);
1285#if USE_MN_THREADS
1286 // The parent's waiters do not exist in the child, and the armings
1287 // belong to the closed event backend: a stale entry would satisfy
1288 // fd_waiters_arm's want == armed_flags check and never arm the new
1289 // backend (a lost wake the old dynamic map also had).
1290 for (unsigned int ci = 0; ci < FDMAP_MAX_CHUNKS; ci++) {
1291 struct rb_fd_waiters *chunk = timer_th.fdmap_chunks[ci];
1292 if (chunk == NULL) continue;
1293 for (unsigned int i = 0; i < FDMAP_CHUNK_SIZE; i++) {
1294 ccan_list_head_init(&chunk[i].waiters);
1295 chunk[i].armed_flags = 0;
1296 chunk[i].generation++;
1297 }
1298 }
1299#endif
1300#if HAVE_SYS_EPOLL_H && USE_MN_THREADS
1301 close_invalidate(&timer_th.event_fd, "close event_fd");
1302#elif HAVE_SYS_EVENT_H && USE_MN_THREADS
1303 // A kqueue is not inherited across fork: the number names a closed
1304 // fd in the child, and closing it could hit a reused one.
1305 timer_th.event_fd = -1;
1306#endif
1307 // No mutex_destroy for waiting_lock: glibc returns EBUSY (and
1308 // rb_native_mutex_destroy rb_bugs) for a mutex another ractor's
1309 // M:N thread held at the fork moment. The initialize below
1310 // starts over.
1311 }
1312
1313#if USE_MN_THREADS
1314 for (int lvl = 0; lvl < TIMER_WHEEL_LEVELS; lvl++) {
1315 timer_th.wheel[lvl].occupied = 0;
1316 for (int slot = 0; slot < TIMER_WHEEL_SLOTS; slot++) {
1317 ccan_list_head_init(&timer_th.wheel[lvl].slots[slot]);
1318 }
1319 }
1320 timer_th.wheel_cursor_tick = timer_wheel_tick(rb_hrtime_now());
1321 timer_th.next_expiry = TIMER_WHEEL_NO_EXPIRY;
1322 rb_native_mutex_initialize(&timer_th.waiting_lock);
1323 for (int i = 0; i < IO_WAIT_SHARDS; i++) {
1324 rb_native_mutex_initialize(&timer_th.fd_shard_locks[i]);
1325 }
1326 rb_native_mutex_initialize(&timer_th.wake_pending_lock);
1327 rb_native_cond_initialize(&timer_th.wake_pending_cond);
1328#endif
1329
1330 // open communication channel
1331 setup_communication_pipe_internal(timer_th.comm_fds);
1332
1333 // open event fd
1334 timer_thread_setup_mn();
1335 }
1336
1337 int err = pthread_create(&timer_th.pthread_id, NULL, timer_thread_func, GET_VM());
1338 if (err != 0) {
1339 // The timer thread delivers signals and drives the M:N scheduler;
1340 // running without one only defers the failure to stranger places.
1341 rb_bug_errno("pthread_create (timer thread)", err);
1342 }
1343}
1344
1345static int
1346native_stop_timer_thread(void)
1347{
1348 RUBY_ATOMIC_SET(system_working, 0);
1349
1350 RUBY_DEBUG_LOG("wakeup send %d", timer_th.comm_fds[1]);
1351 timer_thread_wakeup_force();
1352 RUBY_DEBUG_LOG("wakeup sent");
1353 pthread_join(timer_th.pthread_id, NULL);
1354
1355 if (TT_DEBUG) fprintf(stderr, "stop timer thread\n");
1356
1357 return 1;
1358}
1359
1360static void
1361native_reset_timer_thread(void)
1362{
1363 //
1364}
1365
1366#ifdef HAVE_SIGALTSTACK
1367int
1368ruby_stack_overflowed_p(const rb_thread_t *th, const void *addr)
1369{
1370 void *base;
1371 size_t size;
1372 const size_t water_mark = RB_THREAD_PAGE_SIZE;
1373 STACK_GROW_DIR_DETECTION;
1374
1375 if (th) {
1376 size = th->ec->machine.stack_maxsize;
1377 base = (char *)th->ec->machine.stack_start - STACK_DIR_UPPER(0, size);
1378 }
1379#ifdef STACKADDR_AVAILABLE
1380 else if (get_stack(&base, &size) == 0) {
1381# ifdef __APPLE__
1382 // th is NULL in this branch; ask about the calling thread itself.
1383 if (pthread_equal(pthread_self(), native_main_thread.id)) {
1384 struct rlimit rlim;
1385 if (getrlimit(RLIMIT_STACK, &rlim) == 0 && rlim.rlim_cur > size) {
1386 size = (size_t)rlim.rlim_cur;
1387 }
1388 }
1389# endif
1390 base = (char *)base + STACK_DIR_UPPER(+size, -size);
1391 }
1392#endif
1393 else {
1394 return 0;
1395 }
1396
1397 if (size > water_mark) size = water_mark;
1398 if (IS_STACK_DIR_UPPER()) {
1399 if (size > ~(size_t)base+1) size = ~(size_t)base+1;
1400 if (addr > base && addr <= (void *)((char *)base + size)) return 1;
1401 }
1402 else {
1403 if (size > (size_t)base) size = (size_t)base;
1404 if (addr > (void *)((char *)base - size) && addr <= base) return 1;
1405 }
1406 return 0;
1407}
1408#endif
1409
1410int
1411rb_reserved_fd_p(int fd)
1412{
1413 /* no false-positive if out-of-FD at startup */
1414 if (fd < 0) return 0;
1415
1416 if (fd == timer_th.comm_fds[0] ||
1417 fd == timer_th.comm_fds[1]
1418#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1419 || fd == timer_th.event_fd
1420#endif
1421 ) {
1422 goto check_fork_gen;
1423 }
1424 return 0;
1425
1426 check_fork_gen:
1427 if (timer_th.created_fork_gen == current_fork_gen) {
1428 /* async-signal-safe */
1429 return 1;
1430 }
1431 else {
1432 return 0;
1433 }
1434}
1435
1436rb_nativethread_id_t
1438{
1439 return pthread_self();
1440}
1441
1442#if defined(USE_POLL) && !defined(HAVE_PPOLL)
1443/* TODO: don't ignore sigmask */
1444static int
1445ruby_ppoll(struct pollfd *fds, nfds_t nfds,
1446 const struct timespec *ts, const sigset_t *sigmask)
1447{
1448 int timeout_ms;
1449
1450 if (ts) {
1451 int tmp, tmp2;
1452
1453 if (ts->tv_sec > INT_MAX/1000)
1454 timeout_ms = INT_MAX;
1455 else {
1456 tmp = (int)(ts->tv_sec * 1000);
1457 /* round up 1ns to 1ms to avoid excessive wakeups for <1ms sleep */
1458 tmp2 = (int)((ts->tv_nsec + 999999L) / (1000L * 1000L));
1459 if (INT_MAX - tmp < tmp2)
1460 timeout_ms = INT_MAX;
1461 else
1462 timeout_ms = (int)(tmp + tmp2);
1463 }
1464 }
1465 else
1466 timeout_ms = -1;
1467
1468 return poll(fds, nfds, timeout_ms);
1469}
1470# define ppoll(fds,nfds,ts,sigmask) ruby_ppoll((fds),(nfds),(ts),(sigmask))
1471#endif
1472
1473
1474// fork read-write lock (only for pthread)
1475static pthread_rwlock_t rb_thread_fork_rw_lock = PTHREAD_RWLOCK_INITIALIZER;
1476
1477void
1478rb_thread_release_fork_lock(void)
1479{
1480 int r;
1481 if ((r = pthread_rwlock_unlock(&rb_thread_fork_rw_lock))) {
1482 rb_bug_errno("pthread_rwlock_unlock", r);
1483 }
1484}
1485
1486void
1487rb_thread_reset_fork_lock(void)
1488{
1489 int r;
1490 if ((r = pthread_rwlock_destroy(&rb_thread_fork_rw_lock))) {
1491 rb_bug_errno("pthread_rwlock_destroy", r);
1492 }
1493
1494 if ((r = pthread_rwlock_init(&rb_thread_fork_rw_lock, NULL))) {
1495 rb_bug_errno("pthread_rwlock_init", r);
1496 }
1497}
1498
1499void *
1500rb_thread_prevent_fork(void *(*func)(void *), void *data)
1501{
1502 int r;
1503 if ((r = pthread_rwlock_rdlock(&rb_thread_fork_rw_lock))) {
1504 rb_bug_errno("pthread_rwlock_rdlock", r);
1505 }
1506 void *result = func(data);
1507 rb_thread_release_fork_lock();
1508 return result;
1509}
1510
1511void
1512rb_thread_acquire_fork_lock(void)
1513{
1514 int r;
1515 if ((r = pthread_rwlock_wrlock(&rb_thread_fork_rw_lock))) {
1516 rb_bug_errno("pthread_rwlock_wrlock", r);
1517 }
1518}
1519
1520// thread internal event hooks (only for pthread)
1521
1522struct rb_internal_thread_event_hook {
1523 rb_internal_thread_event_callback callback;
1524 rb_event_flag_t event;
1525 void *user_data;
1526
1527 struct rb_internal_thread_event_hook *next;
1528};
1529
1530static pthread_rwlock_t rb_internal_thread_event_hooks_rw_lock = PTHREAD_RWLOCK_INITIALIZER;
1531
1532/* For the GC: whether any thread-event hook is registered right now. The rwlock
1533 * makes the answer happen-after any completed registration; a hook registered
1534 * after this read gets no event from the asking thread (rb_thread_execute_hooks
1535 * skips a swept thread), so it never sees the objects the caller may collect. */
1536bool
1537rb_thread_event_hooks_registered_p(void)
1538{
1539 int r;
1540 if ((r = pthread_rwlock_rdlock(&rb_internal_thread_event_hooks_rw_lock))) {
1541 rb_bug_errno("pthread_rwlock_rdlock", r);
1542 }
1543 const bool registered = (rb_internal_thread_event_hooks != NULL);
1544 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1545 rb_bug_errno("pthread_rwlock_unlock", r);
1546 }
1547 return registered;
1548}
1549
1550#if defined(HAVE_WORKING_FORK)
1551static void
1552rb_internal_thread_event_hooks_rw_lock_atfork(void)
1553{
1554 // After fork(), this rwlock may have been held by a now-dead thread.
1555 //
1556 // pthread_rwlock_destroy() on a held lock is undefined behavior, and
1557 // pthread_rwlock_init() on an already-initialized lock is also undefined
1558 // behavior
1559 //
1560 // Direct assignment of PTHREAD_RWLOCK_INITIALIZER is safe and portable.
1561 rb_internal_thread_event_hooks_rw_lock =
1562 (pthread_rwlock_t)PTHREAD_RWLOCK_INITIALIZER;
1563}
1564#endif
1565
1566rb_internal_thread_event_hook_t *
1567rb_internal_thread_add_event_hook(rb_internal_thread_event_callback callback, rb_event_flag_t internal_event, void *user_data)
1568{
1569 rb_internal_thread_event_hook_t *hook = ALLOC_N(rb_internal_thread_event_hook_t, 1);
1570 hook->callback = callback;
1571 hook->user_data = user_data;
1572 hook->event = internal_event;
1573
1574 int r;
1575 if ((r = pthread_rwlock_wrlock(&rb_internal_thread_event_hooks_rw_lock))) {
1576 rb_bug_errno("pthread_rwlock_wrlock", r);
1577 }
1578
1579 hook->next = rb_internal_thread_event_hooks;
1580 ATOMIC_PTR_EXCHANGE(rb_internal_thread_event_hooks, hook);
1581
1582 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1583 rb_bug_errno("pthread_rwlock_unlock", r);
1584 }
1585 return hook;
1586}
1587
1588bool
1589rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t * hook)
1590{
1591 int r;
1592 if ((r = pthread_rwlock_wrlock(&rb_internal_thread_event_hooks_rw_lock))) {
1593 rb_bug_errno("pthread_rwlock_wrlock", r);
1594 }
1595
1596 bool success = FALSE;
1597
1598 if (rb_internal_thread_event_hooks == hook) {
1599 ATOMIC_PTR_EXCHANGE(rb_internal_thread_event_hooks, hook->next);
1600 success = TRUE;
1601 }
1602 else {
1603 rb_internal_thread_event_hook_t *h = rb_internal_thread_event_hooks;
1604
1605 do {
1606 if (h->next == hook) {
1607 h->next = hook->next;
1608 success = TRUE;
1609 break;
1610 }
1611 } while ((h = h->next));
1612 }
1613
1614 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1615 rb_bug_errno("pthread_rwlock_unlock", r);
1616 }
1617
1618 if (success) {
1619 SIZED_FREE(hook);
1620 }
1621 return success;
1622}
1623
1624static void
1625rb_thread_execute_hooks(rb_event_flag_t event, rb_thread_t *th)
1626{
1627 int r;
1628
1629 /* th->self == 0: the dying thread's final collection swept its Thread wrapper, so
1630 * no hook existed then; one registered since has no ordering claim to this event. */
1631 if (th->self == 0) return;
1632 if ((r = pthread_rwlock_rdlock(&rb_internal_thread_event_hooks_rw_lock))) {
1633 rb_bug_errno("pthread_rwlock_rdlock", r);
1634 }
1635
1636 if (rb_internal_thread_event_hooks) {
1637 rb_internal_thread_event_hook_t *h = rb_internal_thread_event_hooks;
1638 do {
1639 if (h->event & event) {
1640 rb_internal_thread_event_data_t event_data = {
1641 .thread = th->self,
1642 };
1643 (*h->callback)(event, &event_data, h->user_data);
1644 }
1645 } while((h = h->next));
1646 }
1647 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1648 rb_bug_errno("pthread_rwlock_unlock", r);
1649 }
1650}
1651
1652#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:1473
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:4074
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:1183
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: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