12#ifdef THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
14#include "internal/gc.h"
15#include "internal/sanitizers.h"
17#ifdef HAVE_SYS_RESOURCE_H
18#include <sys/resource.h>
20#ifdef HAVE_THR_STKSEGMENT
23#if defined(HAVE_FCNTL_H)
25#elif defined(HAVE_SYS_FCNTL_H)
28#ifdef HAVE_SYS_PRCTL_H
31#if defined(HAVE_SYS_TIME_H)
38#include <sys/syscall.h>
46# include <AvailabilityMacros.h>
49#if defined(HAVE_SYS_EVENTFD_H) && defined(HAVE_EVENTFD)
50# define USE_EVENTFD (1)
51# include <sys/eventfd.h>
53# define USE_EVENTFD (0)
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;
62static const void *
const condattr_monotonic = NULL;
68#define RB_NATIVE_COND_HRTIME_DEADLINE_P() (condattr_monotonic != NULL)
72#define COROUTINE_TARGET_MAY_BE_FREED 1
76#ifndef HAVE_SYS_EVENT_H
77#define HAVE_SYS_EVENT_H 0
80#ifndef HAVE_SYS_EPOLL_H
81#define HAVE_SYS_EPOLL_H 0
89 #if defined(__EMSCRIPTEN__) || defined(COROUTINE_PTHREAD_CONTEXT)
92 #define USE_MN_THREADS 0
93 #elif HAVE_SYS_EPOLL_H
94 #include <sys/epoll.h>
96 #define USE_MN_THREADS 1
99 #define USE_MN_THREADS 0
101 #elif HAVE_SYS_EVENT_H
102 #include <sys/event.h>
103 #define USE_MN_THREADS 1
105 #define USE_MN_THREADS 0
109#ifdef HAVE_SCHED_YIELD
110#define native_thread_yield() (void)sched_yield()
112#define native_thread_yield() ((void)0)
117#define NATIVE_MUTEX_LOCK_DEBUG 0
118#define NATIVE_MUTEX_LOCK_DEBUG_YIELD 0
121mutex_debug(
const char *msg,
void *lock)
123 if (NATIVE_MUTEX_LOCK_DEBUG) {
125 static pthread_mutex_t dbglock = PTHREAD_MUTEX_INITIALIZER;
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);}
137#if NATIVE_MUTEX_LOCK_DEBUG_YIELD
138 native_thread_yield();
140 mutex_debug(
"lock", lock);
141 if ((r = pthread_mutex_lock(lock)) != 0) {
150 mutex_debug(
"unlock", lock);
151 if ((r = pthread_mutex_unlock(lock)) != 0) {
160 mutex_debug(
"trylock", lock);
161 if ((r = pthread_mutex_trylock(lock)) != 0) {
175 int r = pthread_mutex_init(lock, 0);
176 mutex_debug(
"init", lock);
185 int r = pthread_mutex_destroy(lock);
186 mutex_debug(
"destroy", lock);
195 int r = pthread_cond_init(cond, condattr_monotonic);
204 int r = pthread_cond_destroy(cond);
225 r = pthread_cond_signal(cond);
226 }
while (r == EAGAIN);
237 r = pthread_cond_broadcast(cond);
238 }
while (r == EAGAIN);
247 int r = pthread_cond_wait(cond, mutex);
254native_cond_timedwait(rb_nativethread_cond_t *cond, pthread_mutex_t *mutex,
const rb_hrtime_t *abs)
266 rb_hrtime2timespec(&ts, abs);
267 r = pthread_cond_timedwait(cond, mutex, &ts);
268 }
while (r == EINTR);
270 if (r != 0 && r != ETIMEDOUT) {
278native_cond_timeout(rb_nativethread_cond_t *cond,
const rb_hrtime_t rel)
280 if (condattr_monotonic) {
281 return rb_hrtime_add(rb_hrtime_now(), rel);
287 return rb_hrtime_add(rb_timespec2hrtime(&ts), rel);
294 rb_hrtime_t hrmsec = native_cond_timeout(cond, RB_HRTIME_PER_MSEC * msec);
295 native_cond_timedwait(cond, mutex, &hrmsec);
300static rb_internal_thread_event_hook_t *rb_internal_thread_event_hooks = NULL;
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); \
328#define RB_INTERNAL_THREAD_HOOK(event, th) if (UNLIKELY(rb_internal_thread_event_hooks)) { rb_thread_execute_hooks(event, th); }
331static rb_serial_t current_fork_gen = 1;
333#if defined(SIGVTALRM) && !defined(__EMSCRIPTEN__)
334# define USE_UBF_LIST 1
338static void nt_machine_stack_atfork(
void);
346struct rb_thread_context {
357#ifdef RB_THREAD_T_HAS_NATIVE_ID
359get_native_thread_id(
void)
362 return (
int)syscall(SYS_gettid);
363#elif defined(__FreeBSD__)
364 return pthread_getthreadid_np();
370#ifdef RB_THREAD_LOCAL_SPECIFIER
371static RB_THREAD_LOCAL_SPECIFIER
rb_thread_t *ruby_native_thread;
373static pthread_key_t ruby_native_thread_key;
385ruby_thread_from_native(
void)
387#ifdef RB_THREAD_LOCAL_SPECIFIER
388 return ruby_native_thread;
390 return pthread_getspecific(ruby_native_thread_key);
399 ccan_list_node_init(&th->sched.node.ubf);
406 rb_ractor_set_current_ec(th->ractor, th->ec);
408#ifdef RB_THREAD_LOCAL_SPECIFIER
409 ruby_native_thread = th;
412 return pthread_setspecific(ruby_native_thread_key, th) == 0;
420static size_t RB_THREAD_PAGE_SIZE;
426 RB_THREAD_PAGE_SIZE = sysconf(_SC_PAGESIZE);
428#if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK)
429 if (condattr_monotonic) {
430 int r = pthread_condattr_init(condattr_monotonic);
432 r = pthread_condattr_setclock(condattr_monotonic, CLOCK_MONOTONIC);
434 if (r) condattr_monotonic = NULL;
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)");
442 if (pthread_key_create(&ruby_current_ec_key, 0) == EAGAIN) {
443 rb_bug(
"pthread_key_create failed (ruby_current_ec_key)");
446 ruby_posix_signal(SIGVTALRM, null_func);
450 thread_sched_init_vm(vm);
453 main_th->nt->thread_id = pthread_self();
454 main_th->nt->serial = 1;
458 ruby_thread_set_native(main_th);
459 native_thread_setup(main_th->nt);
460 native_thread_setup_on_thread(main_th->nt);
462 TH_SCHED(main_th)->running = main_th;
463 main_th->has_dedicated_nt = 1;
466 main_th->nt->dedicated = 1;
467 main_th->nt->running_thread = main_th;
468 main_th->nt->vm = vm;
470 thread_sched_setup_running_threads(TH_SCHED(main_th), main_th->ractor, vm, main_th, NULL);
473#if USE_RUBY_DEBUG_LOG
474 vm->ractor.sched.dnt_cnt = 1;
494 RB_ALTSTACK_FREE(nt->altstack);
495 SIZED_FREE(nt->nt_context);
507 native_thread_destroy_atfork(nt);
517#ifdef USE_SIGALTSTACK
518 stack_t disable = {0};
519 disable.ss_flags = SS_DISABLE;
520 sigaltstack(&disable, NULL);
522 native_thread_destroy(nt);
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
541#ifndef MAINSTACKADDR_AVAILABLE
542# ifdef STACKADDR_AVAILABLE
543# define MAINSTACKADDR_AVAILABLE 1
545# define MAINSTACKADDR_AVAILABLE 0
548#if MAINSTACKADDR_AVAILABLE && !defined(get_main_stack)
549# define get_main_stack(addr, size) get_stack(addr, size)
552#ifdef STACKADDR_AVAILABLE
557get_stack(
void **addr,
size_t *size)
559#define CHECK_ERR(expr) \
560 {int err = (expr); if (err) return err;}
561#ifdef HAVE_PTHREAD_GETATTR_NP
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));
570 CHECK_ERR(pthread_attr_getstackaddr(&attr, addr));
571 CHECK_ERR(pthread_attr_getstacksize(&attr, size));
573# ifdef HAVE_PTHREAD_ATTR_GETGUARDSIZE
574 CHECK_ERR(pthread_attr_getguardsize(&attr, &guard));
576 guard = RB_THREAD_PAGE_SIZE;
579 pthread_attr_destroy(&attr);
580#elif defined HAVE_PTHREAD_ATTR_GET_NP
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));
587 CHECK_ERR(pthread_attr_getstackaddr(&attr, addr));
588 CHECK_ERR(pthread_attr_getstacksize(&attr, size));
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)
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
598# if defined HAVE_THR_STKSEGMENT
599 CHECK_ERR(thr_stksegment(&stk));
601 CHECK_ERR(pthread_stackseg_np(pthread_self(), &stk));
605#elif defined HAVE_PTHREAD_GETTHRDS_NP
606 pthread_t th = pthread_self();
607 struct __pthrdsinfo thinfo;
609 int regsiz=
sizeof(reg);
610 CHECK_ERR(pthread_getthrds_np(&th, PTHRDSINFO_QUERY_ALL,
611 &thinfo,
sizeof(thinfo),
613 *addr = 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__
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));
627#error STACKADDR_AVAILABLE is defined but not implemented.
635 rb_nativethread_id_t id;
636 size_t stack_maxsize;
640#ifdef STACK_END_ADDRESS
641extern void *STACK_END_ADDRESS;
645native_thread_init_main_thread_stack(
void *addr)
647 native_main_thread.id = pthread_self();
648#ifdef RUBY_ASAN_ENABLED
649 addr = asan_get_real_stack_addr((
void *)addr);
652#if MAINSTACKADDR_AVAILABLE
653 if (native_main_thread.stack_maxsize)
return;
657 if (get_main_stack(&stackaddr, &size) == 0) {
658 native_main_thread.stack_maxsize = size;
659 native_main_thread.stack_start = stackaddr;
664#ifdef STACK_END_ADDRESS
665 native_main_thread.stack_start = STACK_END_ADDRESS;
667 if (!native_main_thread.stack_start ||
668 STACK_UPPER((
VALUE *)(
void *)&addr,
669 native_main_thread.stack_start > (
VALUE *)addr,
670 native_main_thread.stack_start < (
VALUE *)addr)) {
671 native_main_thread.stack_start = (
VALUE *)addr;
675#if defined(HAVE_GETRLIMIT)
676#if defined(PTHREAD_STACK_DEFAULT)
677 size_t size = PTHREAD_STACK_DEFAULT;
679 size_t size = RUBY_VM_THREAD_VM_STACK_SIZE;
683 STACK_GROW_DIR_DETECTION;
684 if (getrlimit(RLIMIT_STACK, &rlim) == 0) {
685 size = (size_t)rlim.rlim_cur;
687 addr = native_main_thread.stack_start;
688 if (IS_STACK_DIR_UPPER()) {
689 space = ((size_t)((
char *)addr + size) / RB_THREAD_PAGE_SIZE) * RB_THREAD_PAGE_SIZE - (size_t)addr;
692 space = (size_t)addr - ((
size_t)((
char *)addr - size) / RB_THREAD_PAGE_SIZE + 1) * RB_THREAD_PAGE_SIZE;
694 native_main_thread.stack_maxsize = space;
698#if MAINSTACKADDR_AVAILABLE
705 STACK_GROW_DIR_DETECTION;
707 if (IS_STACK_DIR_UPPER()) {
708 start = native_main_thread.stack_start;
709 end = (
char *)native_main_thread.stack_start + native_main_thread.stack_maxsize;
712 start = (
char *)native_main_thread.stack_start - native_main_thread.stack_maxsize;
713 end = native_main_thread.stack_start;
716 if ((
void *)addr < start || (
void *)addr > end) {
718 native_main_thread.stack_start = (
VALUE *)addr;
719 native_main_thread.stack_maxsize = 0;
724#define CHECK_ERR(expr) \
725 {int err = (expr); if (err) {rb_bug_errno(#expr, err);}}
728native_thread_init_stack(
rb_thread_t *th,
void *local_in_parent_frame)
730 rb_nativethread_id_t curr = pthread_self();
731#ifdef RUBY_ASAN_ENABLED
732 local_in_parent_frame = asan_get_real_stack_addr(local_in_parent_frame);
733 th->ec->machine.asan_fake_stack_handle = asan_get_thread_fake_stack_handle();
736 if (!native_main_thread.id) {
739 native_thread_init_main_thread_stack(local_in_parent_frame);
742 if (pthread_equal(curr, native_main_thread.id)) {
743 th->ec->machine.stack_start = native_main_thread.stack_start;
744 th->ec->machine.stack_maxsize = native_main_thread.stack_maxsize;
747#ifdef STACKADDR_AVAILABLE
748 if (th_has_dedicated_nt(th)) {
752 if (get_stack(&start, &size) == 0) {
753 uintptr_t diff = (uintptr_t)start - (uintptr_t)local_in_parent_frame;
754 th->ec->machine.stack_start = local_in_parent_frame;
755 th->ec->machine.stack_maxsize = size - diff;
759 rb_raise(
rb_eNotImpError,
"ruby engine can initialize only in the main thread");
778 const size_t stack_size = nt->vm->default_params.thread_machine_stack_size;
780#ifdef USE_SIGALTSTACK
781 nt->altstack = rb_allocate_sigaltstack();
784 CHECK_ERR(pthread_attr_init(&attr));
786# ifdef PTHREAD_STACK_MIN
787 RUBY_DEBUG_LOG(
"stack size: %lu", (
unsigned long)stack_size);
788 CHECK_ERR(pthread_attr_setstacksize(&attr, stack_size));
791# ifdef HAVE_PTHREAD_ATTR_SETINHERITSCHED
792 CHECK_ERR(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED));
794 CHECK_ERR(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
796 err = pthread_create(&nt->thread_id, &attr, nt_start, nt);
798 RUBY_DEBUG_LOG(
"nt:%d err:%d", (
int)nt->serial, err);
800 CHECK_ERR(pthread_attr_destroy(&attr));
818#ifdef RB_THREAD_T_HAS_NATIVE_ID
819 nt->tid = get_native_thread_id();
823 RB_ALTSTACK_INIT(nt->altstack, nt->altstack);
827native_thread_alloc(
void)
830 native_thread_setup(nt);
836#if USE_RUBY_DEBUG_LOG
846#if USE_NATIVE_THREAD_PRIORITY
851#if defined(_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING > 0)
852 struct sched_param sp;
854 int priority = 0 - th->priority;
856 pthread_getschedparam(th->nt->thread_id, &policy, &sp);
857 max = sched_get_priority_max(policy);
858 min = sched_get_priority_min(policy);
860 if (min > priority) {
863 else if (max < priority) {
867 sp.sched_priority = priority;
868 pthread_setschedparam(th->nt->thread_id, policy, &sp);
879 return rb_fd_select(n, readfds, writefds, exceptfds, timeout);
889 pthread_kill(th->nt->thread_id, SIGVTALRM);
893native_thread_default_max_cpu(
void)
895#if defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
896 long nprocessors = sysconf(_SC_NPROCESSORS_ONLN);
897 return (nprocessors > 0) ? (int)nprocessors : 8;
905#define WRITE_CONST(fd, str) (void)(write((fd),(str),sizeof(str)-1)<0)
908rb_thread_wakeup_timer_thread(
int sig)
914 timer_thread_wakeup_force();
925 RUBY_VM_SET_TRAP_INTERRUPT(main_th_ec);
927 if (vm->ubf_async_safe && main_th->unblock.func) {
928 (main_th->unblock.func)(main_th->unblock.arg);
935#define CLOSE_INVALIDATE_PAIR(expr) \
936 close_invalidate_pair(expr,"close_invalidate: "#expr)
938close_invalidate(
int *fdp,
const char *msg)
944 async_bug_fd(msg,
errno, fd);
949close_invalidate_pair(
int fds[2],
const char *msg)
951 if (USE_EVENTFD && fds[0] == fds[1]) {
953 close_invalidate(&fds[0], msg);
956 close_invalidate(&fds[1], msg);
957 close_invalidate(&fds[0], msg);
967 oflags = fcntl(fd, F_GETFL);
970 oflags |= O_NONBLOCK;
971 err = fcntl(fd, F_SETFL, oflags);
978setup_communication_pipe_internal(
int pipes[2])
982 if (pipes[0] > 0 || pipes[1] > 0) {
983 VM_ASSERT(pipes[0] > 0);
984 VM_ASSERT(pipes[1] > 0);
992#if USE_EVENTFD && defined(EFD_NONBLOCK) && defined(EFD_CLOEXEC)
993 pipes[0] = pipes[1] = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);
1003 rb_bug(
"can not create communication pipe");
1007 set_nonblock(pipes[0]);
1008 set_nonblock(pipes[1]);
1011#if !defined(SET_CURRENT_THREAD_NAME) && defined(__linux__) && defined(PR_SET_NAME)
1012# define SET_CURRENT_THREAD_NAME(name) prctl(PR_SET_NAME, name)
1017#if defined(__linux__)
1019#elif defined(__APPLE__)
1032#ifdef SET_CURRENT_THREAD_NAME
1034 if (!
NIL_P(loc = th->name)) {
1035 SET_CURRENT_THREAD_NAME(RSTRING_PTR(loc));
1037 else if ((loc = threadptr_invoke_proc_location(th)) !=
Qnil) {
1039 char buf[THREAD_NAME_MAX];
1044 p = strrchr(name,
'/');
1052 if (
len >=
sizeof(buf)) {
1053 buf[
sizeof(buf)-2] =
'*';
1054 buf[
sizeof(buf)-1] =
'\0';
1056 SET_CURRENT_THREAD_NAME(buf);
1062native_set_another_thread_name(rb_nativethread_id_t thread_id,
VALUE name)
1064#if defined SET_ANOTHER_THREAD_NAME || defined SET_CURRENT_THREAD_NAME
1065 char buf[THREAD_NAME_MAX];
1067# if !defined SET_ANOTHER_THREAD_NAME
1068 if (!pthread_equal(pthread_self(), thread_id))
return;
1073 if (n >= (
int)
sizeof(buf)) {
1074 memcpy(buf, s,
sizeof(buf)-1);
1075 buf[
sizeof(buf)-1] =
'\0';
1079# if defined SET_ANOTHER_THREAD_NAME
1080 SET_ANOTHER_THREAD_NAME(thread_id, s);
1081# elif defined SET_CURRENT_THREAD_NAME
1082 SET_CURRENT_THREAD_NAME(s);
1087#if defined(RB_THREAD_T_HAS_NATIVE_ID) || defined(__APPLE__)
1089native_thread_native_thread_id(
rb_thread_t *target_th)
1091 if (!target_th->nt)
return Qnil;
1093#ifdef RB_THREAD_T_HAS_NATIVE_ID
1094 int tid = target_th->nt->tid;
1095 if (tid == 0)
return Qnil;
1097#elif defined(__APPLE__)
1103# if (!defined(MAC_OS_X_VERSION_10_6) || \
1104 (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6) || \
1105 defined(__POWERPC__) )
1106 const bool no_pthread_threadid_np =
true;
1107# define NO_PTHREAD_MACH_THREAD_NP 1
1108# elif MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
1109 const bool no_pthread_threadid_np =
false;
1111# if !(defined(__has_attribute) && __has_attribute(availability))
1113 __attribute__((weak))
int pthread_threadid_np(pthread_t, uint64_t*);
1116 const bool no_pthread_threadid_np = !&pthread_threadid_np;
1118 if (no_pthread_threadid_np) {
1119 return ULL2NUM(pthread_mach_thread_np(pthread_self()));
1121# ifndef NO_PTHREAD_MACH_THREAD_NP
1122 int e = pthread_threadid_np(target_th->nt->thread_id, &tid);
1124 return ULL2NUM((
unsigned long long)tid);
1128# define USE_NATIVE_THREAD_NATIVE_THREAD_ID 1
1130# define USE_NATIVE_THREAD_NATIVE_THREAD_ID 0
1134 rb_serial_t created_fork_gen;
1135 pthread_t pthread_id;
1139#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1142#if HAVE_SYS_EPOLL_H && USE_MN_THREADS
1143#define EPOLL_EVENTS_MAX 0x10
1144 struct epoll_event finished_events[EPOLL_EVENTS_MAX];
1145#elif HAVE_SYS_EVENT_H && USE_MN_THREADS
1146#define KQUEUE_EVENTS_MAX 0x10
1147 struct kevent finished_events[KQUEUE_EVENTS_MAX];
1154#define TIMER_WHEEL_LEVELS 4
1155#define TIMER_WHEEL_SLOT_BITS 6
1156#define TIMER_WHEEL_SLOTS (1 << TIMER_WHEEL_SLOT_BITS)
1157 struct timer_wheel_level {
1159 struct ccan_list_head slots[TIMER_WHEEL_SLOTS];
1160 } wheel[TIMER_WHEEL_LEVELS];
1161 uint64_t wheel_cursor_tick;
1162 rb_hrtime_t next_expiry;
1163 pthread_mutex_t waiting_lock;
1169#define IO_WAIT_SHARDS 16
1170 pthread_mutex_t fd_shard_locks[IO_WAIT_SHARDS];
1173 pthread_mutex_t wake_pending_lock;
1174 rb_nativethread_cond_t wake_pending_cond;
1177#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1181#define FDMAP_MAX_CHUNKS 1024
1185 .created_fork_gen = 0,
1188#define TIMER_THREAD_CREATED_P() (timer_th.created_fork_gen == current_fork_gen)
1190static void timer_thread_check_timeslice(
rb_vm_t *vm);
1191static bool timeslice_scan(
rb_vm_t *vm,
bool interrupt);
1192static int timer_thread_set_timeout(
rb_vm_t *vm);
1194#include "thread_sched_mn.c"
1201 pthread_sigmask(0, NULL, &oldmask);
1202 if (sigismember(&oldmask, SIGVTALRM)) {
1206 RUBY_DEBUG_LOG(
"ok");
1213signal_communication_pipe(
int fd)
1216 const uint64_t buff = 1;
1218 const char buff =
'!';
1225 if ((result = write(fd, &buff,
sizeof(buff))) <= 0) {
1228 case EINTR:
goto retry;
1230#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1235 async_bug_fd(
"rb_thread_wakeup_timer_thread: write", e, fd);
1238 if (TT_DEBUG) WRITE_CONST(2,
"rb_thread_wakeup_timer_thread: write\n");
1246timer_thread_wakeup_force(
void)
1249 signal_communication_pipe(timer_th.comm_fds[1]);
1254rb_thread_create_timer_thread(
void)
1256 rb_serial_t created_fork_gen = timer_th.created_fork_gen;
1258 RUBY_DEBUG_LOG(
"fork_gen create:%d current:%d", (
int)created_fork_gen, (
int)current_fork_gen);
1260 timer_th.created_fork_gen = current_fork_gen;
1262 if (created_fork_gen != current_fork_gen) {
1263 if (created_fork_gen != 0) {
1264 RUBY_DEBUG_LOG(
"forked child process");
1266 CLOSE_INVALIDATE_PAIR(timer_th.comm_fds);
1272 for (
unsigned int ci = 0; ci < FDMAP_MAX_CHUNKS; ci++) {
1274 if (chunk == NULL)
continue;
1275 for (
unsigned int i = 0; i < FDMAP_CHUNK_SIZE; i++) {
1276 ccan_list_head_init(&chunk[i].waiters);
1277 chunk[i].armed_flags = 0;
1278 chunk[i].generation++;
1282#if HAVE_SYS_EPOLL_H && USE_MN_THREADS
1283 close_invalidate(&timer_th.event_fd,
"close event_fd");
1284#elif HAVE_SYS_EVENT_H && USE_MN_THREADS
1287 timer_th.event_fd = -1;
1296 for (
int lvl = 0; lvl < TIMER_WHEEL_LEVELS; lvl++) {
1297 timer_th.wheel[lvl].occupied = 0;
1298 for (
int slot = 0; slot < TIMER_WHEEL_SLOTS; slot++) {
1299 ccan_list_head_init(&timer_th.wheel[lvl].slots[slot]);
1302 timer_th.wheel_cursor_tick = timer_wheel_tick(rb_hrtime_now());
1303 timer_th.next_expiry = TIMER_WHEEL_NO_EXPIRY;
1305 for (
int i = 0; i < IO_WAIT_SHARDS; i++) {
1313 setup_communication_pipe_internal(timer_th.comm_fds);
1316 timer_thread_setup_mn();
1319 int err = pthread_create(&timer_th.pthread_id, NULL, timer_thread_func, GET_VM());
1328native_stop_timer_thread(
void)
1332 RUBY_DEBUG_LOG(
"wakeup send %d", timer_th.comm_fds[1]);
1333 timer_thread_wakeup_force();
1334 RUBY_DEBUG_LOG(
"wakeup sent");
1335 pthread_join(timer_th.pthread_id, NULL);
1337 if (TT_DEBUG) fprintf(stderr,
"stop timer thread\n");
1343native_reset_timer_thread(
void)
1348#ifdef HAVE_SIGALTSTACK
1350ruby_stack_overflowed_p(
const rb_thread_t *th,
const void *addr)
1354 const size_t water_mark = RB_THREAD_PAGE_SIZE;
1355 STACK_GROW_DIR_DETECTION;
1358 size = th->ec->machine.stack_maxsize;
1359 base = (
char *)th->ec->machine.stack_start - STACK_DIR_UPPER(0, size);
1361#ifdef STACKADDR_AVAILABLE
1362 else if (get_stack(&base, &size) == 0) {
1365 if (pthread_equal(pthread_self(), native_main_thread.id)) {
1367 if (getrlimit(RLIMIT_STACK, &rlim) == 0 && rlim.rlim_cur > size) {
1368 size = (size_t)rlim.rlim_cur;
1372 base = (
char *)base + STACK_DIR_UPPER(+size, -size);
1379 if (size > water_mark) size = water_mark;
1380 if (IS_STACK_DIR_UPPER()) {
1381 if (size > ~(
size_t)base+1) size = ~(
size_t)base+1;
1382 if (addr > base && addr <= (
void *)((
char *)base + size))
return 1;
1385 if (size > (
size_t)base) size = (
size_t)base;
1386 if (addr > (
void *)((
char *)base - size) && addr <= base)
return 1;
1396 if (fd < 0)
return 0;
1398 if (fd == timer_th.comm_fds[0] ||
1399 fd == timer_th.comm_fds[1]
1400#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
1401 || fd == timer_th.event_fd
1404 goto check_fork_gen;
1409 if (timer_th.created_fork_gen == current_fork_gen) {
1421 return pthread_self();
1424#if defined(USE_POLL) && !defined(HAVE_PPOLL)
1427ruby_ppoll(
struct pollfd *fds, nfds_t nfds,
1428 const struct timespec *ts,
const sigset_t *sigmask)
1435 if (ts->tv_sec > INT_MAX/1000)
1436 timeout_ms = INT_MAX;
1438 tmp = (int)(ts->tv_sec * 1000);
1440 tmp2 = (int)((ts->tv_nsec + 999999L) / (1000L * 1000L));
1441 if (INT_MAX - tmp < tmp2)
1442 timeout_ms = INT_MAX;
1444 timeout_ms = (int)(tmp + tmp2);
1450 return poll(fds, nfds, timeout_ms);
1452# define ppoll(fds,nfds,ts,sigmask) ruby_ppoll((fds),(nfds),(ts),(sigmask))
1457static pthread_rwlock_t rb_thread_fork_rw_lock = PTHREAD_RWLOCK_INITIALIZER;
1460rb_thread_release_fork_lock(
void)
1463 if ((r = pthread_rwlock_unlock(&rb_thread_fork_rw_lock))) {
1469rb_thread_reset_fork_lock(
void)
1472 if ((r = pthread_rwlock_destroy(&rb_thread_fork_rw_lock))) {
1476 if ((r = pthread_rwlock_init(&rb_thread_fork_rw_lock, NULL))) {
1482rb_thread_prevent_fork(
void *(*func)(
void *),
void *data)
1485 if ((r = pthread_rwlock_rdlock(&rb_thread_fork_rw_lock))) {
1488 void *result = func(data);
1489 rb_thread_release_fork_lock();
1494rb_thread_acquire_fork_lock(
void)
1497 if ((r = pthread_rwlock_wrlock(&rb_thread_fork_rw_lock))) {
1504struct rb_internal_thread_event_hook {
1505 rb_internal_thread_event_callback callback;
1509 struct rb_internal_thread_event_hook *next;
1512static pthread_rwlock_t rb_internal_thread_event_hooks_rw_lock = PTHREAD_RWLOCK_INITIALIZER;
1519rb_thread_event_hooks_registered_p(
void)
1522 if ((r = pthread_rwlock_rdlock(&rb_internal_thread_event_hooks_rw_lock))) {
1525 const bool registered = (rb_internal_thread_event_hooks != NULL);
1526 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1532#if defined(HAVE_WORKING_FORK)
1534rb_internal_thread_event_hooks_rw_lock_atfork(
void)
1543 rb_internal_thread_event_hooks_rw_lock =
1544 (pthread_rwlock_t)PTHREAD_RWLOCK_INITIALIZER;
1548rb_internal_thread_event_hook_t *
1551 rb_internal_thread_event_hook_t *hook =
ALLOC_N(rb_internal_thread_event_hook_t, 1);
1552 hook->callback = callback;
1553 hook->user_data = user_data;
1554 hook->event = internal_event;
1557 if ((r = pthread_rwlock_wrlock(&rb_internal_thread_event_hooks_rw_lock))) {
1561 hook->next = rb_internal_thread_event_hooks;
1562 ATOMIC_PTR_EXCHANGE(rb_internal_thread_event_hooks, hook);
1564 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1574 if ((r = pthread_rwlock_wrlock(&rb_internal_thread_event_hooks_rw_lock))) {
1578 bool success = FALSE;
1580 if (rb_internal_thread_event_hooks == hook) {
1581 ATOMIC_PTR_EXCHANGE(rb_internal_thread_event_hooks, hook->next);
1585 rb_internal_thread_event_hook_t *h = rb_internal_thread_event_hooks;
1588 if (h->next == hook) {
1589 h->next = hook->next;
1593 }
while ((h = h->next));
1596 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
1613 if (th->self == 0)
return;
1614 if ((r = pthread_rwlock_rdlock(&rb_internal_thread_event_hooks_rw_lock))) {
1618 if (rb_internal_thread_event_hooks) {
1619 rb_internal_thread_event_hook_t *h = rb_internal_thread_event_hooks;
1621 if (h->event & event) {
1625 (*h->callback)(event, &event_data, h->user_data);
1627 }
while((h = h->next));
1629 if ((r = pthread_rwlock_unlock(&rb_internal_thread_event_hooks_rw_lock))) {
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
#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...
#define RUBY_ATOMIC_LOAD(var)
Atomic load.
#define RUBY_ATOMIC_SET(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except for the return type.
uint32_t rb_event_flag_t
Represents event(s).
#define INT2FIX
Old name of RB_INT2FIX.
#define ZALLOC
Old name of RB_ZALLOC.
#define ALLOC_N
Old name of RB_ALLOC_N.
#define ULL2NUM
Old name of RB_ULL2NUM.
#define NUM2INT
Old name of RB_NUM2INT.
#define Qnil
Old name of RUBY_Qnil.
#define NIL_P
Old name of RB_NIL_P.
VALUE rb_eNotImpError
NotImplementedError exception.
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
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...
int rb_cloexec_pipe(int fildes[2])
Opens a pipe with closing on exec.
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
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.
int len
Length of the buffer.
#define RUBY_INTERNAL_THREAD_EVENT_RESUMED
Triggered when a thread successfully acquired the GVL.
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.
#define RUBY_INTERNAL_THREAD_EVENT_SUSPENDED
Triggered when a thread released the GVL.
#define RUBY_INTERNAL_THREAD_EVENT_STARTED
Triggered when a new thread is started.
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.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
#define rb_fd_select
Waits for multiple file descriptors at once.
#define RARRAY_AREF(a, i)
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
#define errno
Ractor-aware version of errno.
The data structure which wraps the fd_set bitmap used by select(2).
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.