Ruby 3.5.0dev (2025-07-11 revision 214983bd9be88903833558043a20ba1c2469c333)
thread_pthread_mn.c (214983bd9be88903833558043a20ba1c2469c333)
1// included by "thread_pthread.c"
2
3#if USE_MN_THREADS
4
5static void timer_thread_unregister_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags);
6
7static bool
8timer_thread_cancel_waiting(rb_thread_t *th)
9{
10 bool canceled = false;
11
12 if (th->sched.waiting_reason.flags) {
13 rb_native_mutex_lock(&timer_th.waiting_lock);
14 {
15 if (th->sched.waiting_reason.flags) {
16 canceled = true;
17 ccan_list_del_init(&th->sched.waiting_reason.node);
18 if (th->sched.waiting_reason.flags & (thread_sched_waiting_io_read | thread_sched_waiting_io_write)) {
19 timer_thread_unregister_waiting(th, th->sched.waiting_reason.data.fd, th->sched.waiting_reason.flags);
20 }
21 th->sched.waiting_reason.flags = thread_sched_waiting_none;
22 }
23 }
24 rb_native_mutex_unlock(&timer_th.waiting_lock);
25 }
26
27 return canceled;
28}
29
30static void
31ubf_event_waiting(void *ptr)
32{
33 rb_thread_t *th = (rb_thread_t *)ptr;
34 struct rb_thread_sched *sched = TH_SCHED(th);
35
36 RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
37
38 VM_ASSERT(th->nt == NULL || !th_has_dedicated_nt(th));
39
40 // only once. it is safe because th->interrupt_lock is already acquired.
41 th->unblock.func = NULL;
42 th->unblock.arg = NULL;
43
44 bool canceled = timer_thread_cancel_waiting(th);
45
46 thread_sched_lock(sched, th);
47 {
48 if (sched->running == th) {
49 RUBY_DEBUG_LOG("not waiting yet");
50 }
51 else if (canceled) {
52 thread_sched_to_ready_common(sched, th, true, false);
53 }
54 else {
55 RUBY_DEBUG_LOG("already not waiting");
56 }
57 }
58 thread_sched_unlock(sched, th);
59}
60
61static bool timer_thread_register_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags, rb_hrtime_t *rel);
62
63// return true if timed out
64static bool
65thread_sched_wait_events(struct rb_thread_sched *sched, rb_thread_t *th, int fd, enum thread_sched_waiting_flag events, rb_hrtime_t *rel)
66{
67 VM_ASSERT(!th_has_dedicated_nt(th)); // on SNT
68
69 volatile bool timedout = false, need_cancel = false;
70
71 if (timer_thread_register_waiting(th, fd, events, rel)) {
72 RUBY_DEBUG_LOG("wait fd:%d", fd);
73
74 RB_VM_SAVE_MACHINE_CONTEXT(th);
75 ubf_set(th, ubf_event_waiting, (void *)th);
76
77 RB_INTERNAL_THREAD_HOOK(RUBY_INTERNAL_THREAD_EVENT_SUSPENDED, th);
78
79 thread_sched_lock(sched, th);
80 {
81 if (th->sched.waiting_reason.flags == thread_sched_waiting_none) {
82 // already awaken
83 }
84 else if (RUBY_VM_INTERRUPTED(th->ec)) {
85 need_cancel = true;
86 }
87 else {
88 RUBY_DEBUG_LOG("sleep");
89
90 th->status = THREAD_STOPPED_FOREVER;
91 thread_sched_wakeup_next_thread(sched, th, true);
92 thread_sched_wait_running_turn(sched, th, true);
93
94 RUBY_DEBUG_LOG("wakeup");
95 }
96
97 timedout = th->sched.waiting_reason.data.result == 0;
98 }
99 thread_sched_unlock(sched, th);
100
101 if (need_cancel) {
102 timer_thread_cancel_waiting(th);
103 }
104
105 ubf_clear(th); // TODO: maybe it is already NULL?
106
107 th->status = THREAD_RUNNABLE;
108 }
109 else {
110 RUBY_DEBUG_LOG("can not wait fd:%d", fd);
111 return false;
112 }
113
114 VM_ASSERT(sched->running == th);
115
116 return timedout;
117}
118
120
121static int
122get_sysconf_page_size(void)
123{
124 static long page_size = 0;
125
126 if (UNLIKELY(page_size == 0)) {
127 page_size = sysconf(_SC_PAGESIZE);
128 VM_ASSERT(page_size < INT_MAX);
129 }
130 return (int)page_size;
131}
132
133#define MSTACK_CHUNK_SIZE (512 * 1024 * 1024) // 512MB
134#define MSTACK_PAGE_SIZE get_sysconf_page_size()
135#define MSTACK_CHUNK_PAGE_NUM (MSTACK_CHUNK_SIZE / MSTACK_PAGE_SIZE - 1) // 1 is start redzone
136
137// 512MB chunk
138// 131,072 pages (> 65,536)
139// 0th page is Redzone. Start from 1st page.
140
141/*
142 * <--> machine stack + vm stack
143 * ----------------------------------
144 * |HD...|RZ| ... |RZ| ... ... |RZ|
145 * <------------- 512MB ------------->
146 */
147
148static struct nt_stack_chunk_header {
149 struct nt_stack_chunk_header *prev_chunk;
150 struct nt_stack_chunk_header *prev_free_chunk;
151
152 uint16_t start_page;
153 uint16_t stack_count;
154 uint16_t uninitialized_stack_count;
155
156 uint16_t free_stack_pos;
157 uint16_t free_stack[];
158} *nt_stack_chunks = NULL,
159 *nt_free_stack_chunks = NULL;
160
161struct nt_machine_stack_footer {
162 struct nt_stack_chunk_header *ch;
163 size_t index;
164};
165
166static rb_nativethread_lock_t nt_machine_stack_lock = RB_NATIVETHREAD_LOCK_INIT;
167
168#include <sys/mman.h>
169
170// vm_stack_size + machine_stack_size + 1 * (guard page size)
171static inline size_t
172nt_thread_stack_size(void)
173{
174 static size_t msz;
175 if (LIKELY(msz > 0)) return msz;
176
177 rb_vm_t *vm = GET_VM();
178 int sz = (int)(vm->default_params.thread_vm_stack_size + vm->default_params.thread_machine_stack_size + MSTACK_PAGE_SIZE);
179 int page_num = roomof(sz, MSTACK_PAGE_SIZE);
180 msz = (size_t)page_num * MSTACK_PAGE_SIZE;
181 return msz;
182}
183
184static struct nt_stack_chunk_header *
185nt_alloc_thread_stack_chunk(void)
186{
187 int mmap_flags = MAP_ANONYMOUS | MAP_PRIVATE;
188#if defined(MAP_STACK) && !defined(__FreeBSD__) && !defined(__FreeBSD_kernel__)
189 mmap_flags |= MAP_STACK;
190#endif
191
192 const char *m = (void *)mmap(NULL, MSTACK_CHUNK_SIZE, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
193 if (m == MAP_FAILED) {
194 return NULL;
195 }
196
197 ruby_annotate_mmap(m, MSTACK_CHUNK_SIZE, "Ruby:nt_alloc_thread_stack_chunk");
198
199 size_t msz = nt_thread_stack_size();
200 int header_page_cnt = 1;
201 int stack_count = ((MSTACK_CHUNK_PAGE_NUM - header_page_cnt) * MSTACK_PAGE_SIZE) / msz;
202 int ch_size = sizeof(struct nt_stack_chunk_header) + sizeof(uint16_t) * stack_count;
203
204 if (ch_size > MSTACK_PAGE_SIZE * header_page_cnt) {
205 header_page_cnt = (ch_size + MSTACK_PAGE_SIZE - 1) / MSTACK_PAGE_SIZE;
206 stack_count = ((MSTACK_CHUNK_PAGE_NUM - header_page_cnt) * MSTACK_PAGE_SIZE) / msz;
207 }
208
209 VM_ASSERT(stack_count <= UINT16_MAX);
210
211 struct nt_stack_chunk_header *ch = (struct nt_stack_chunk_header *)m;
212
213 ch->start_page = header_page_cnt;
214 ch->prev_chunk = nt_stack_chunks;
215 ch->prev_free_chunk = nt_free_stack_chunks;
216 ch->uninitialized_stack_count = ch->stack_count = (uint16_t)stack_count;
217 ch->free_stack_pos = 0;
218
219 RUBY_DEBUG_LOG("ch:%p start_page:%d stack_cnt:%d stack_size:%d", ch, (int)ch->start_page, (int)ch->stack_count, (int)msz);
220
221 return ch;
222}
223
224static void *
225nt_stack_chunk_get_stack_start(struct nt_stack_chunk_header *ch, size_t idx)
226{
227 const char *m = (char *)ch;
228 return (void *)(m + ch->start_page * MSTACK_PAGE_SIZE + idx * nt_thread_stack_size());
229}
230
231static struct nt_machine_stack_footer *
232nt_stack_chunk_get_msf(const rb_vm_t *vm, const char *mstack)
233{
234 // TODO: stack direction
235 const size_t msz = vm->default_params.thread_machine_stack_size;
236 return (struct nt_machine_stack_footer *)&mstack[msz - sizeof(struct nt_machine_stack_footer)];
237}
238
239static void *
240nt_stack_chunk_get_stack(const rb_vm_t *vm, struct nt_stack_chunk_header *ch, size_t idx, void **vm_stack, void **machine_stack)
241{
242 // TODO: only support stack going down
243 // [VM ... <GUARD> machine stack ...]
244
245 const char *vstack, *mstack;
246 const char *guard_page;
247 vstack = nt_stack_chunk_get_stack_start(ch, idx);
248 guard_page = vstack + vm->default_params.thread_vm_stack_size;
249 mstack = guard_page + MSTACK_PAGE_SIZE;
250
251 struct nt_machine_stack_footer *msf = nt_stack_chunk_get_msf(vm, mstack);
252 msf->ch = ch;
253 msf->index = idx;
254
255#if 0
256 RUBY_DEBUG_LOG("msf:%p vstack:%p-%p guard_page:%p-%p mstack:%p-%p", msf,
257 vstack, (void *)(guard_page-1),
258 guard_page, (void *)(mstack-1),
259 mstack, (void *)(msf));
260#endif
261
262 *vm_stack = (void *)vstack;
263 *machine_stack = (void *)mstack;
264
265 return (void *)guard_page;
266}
267
269static void
270nt_stack_chunk_dump(void)
271{
272 struct nt_stack_chunk_header *ch;
273 int i;
274
275 fprintf(stderr, "** nt_stack_chunks\n");
276 ch = nt_stack_chunks;
277 for (i=0; ch; i++, ch = ch->prev_chunk) {
278 fprintf(stderr, "%d %p free_pos:%d\n", i, (void *)ch, (int)ch->free_stack_pos);
279 }
280
281 fprintf(stderr, "** nt_free_stack_chunks\n");
282 ch = nt_free_stack_chunks;
283 for (i=0; ch; i++, ch = ch->prev_free_chunk) {
284 fprintf(stderr, "%d %p free_pos:%d\n", i, (void *)ch, (int)ch->free_stack_pos);
285 }
286}
287
288static int
289nt_guard_page(const char *p, size_t len)
290{
291 if (mprotect((void *)p, len, PROT_NONE) != -1) {
292 return 0;
293 }
294 else {
295 return errno;
296 }
297}
298
299static int
300nt_alloc_stack(rb_vm_t *vm, void **vm_stack, void **machine_stack)
301{
302 int err = 0;
303
304 rb_native_mutex_lock(&nt_machine_stack_lock);
305 {
306 retry:
307 if (nt_free_stack_chunks) {
308 struct nt_stack_chunk_header *ch = nt_free_stack_chunks;
309 if (ch->free_stack_pos > 0) {
310 RUBY_DEBUG_LOG("free_stack_pos:%d", ch->free_stack_pos);
311 nt_stack_chunk_get_stack(vm, ch, ch->free_stack[--ch->free_stack_pos], vm_stack, machine_stack);
312 }
313 else if (ch->uninitialized_stack_count > 0) {
314 RUBY_DEBUG_LOG("uninitialized_stack_count:%d", ch->uninitialized_stack_count);
315
316 size_t idx = ch->stack_count - ch->uninitialized_stack_count--;
317 void *guard_page = nt_stack_chunk_get_stack(vm, ch, idx, vm_stack, machine_stack);
318 err = nt_guard_page(guard_page, MSTACK_PAGE_SIZE);
319 }
320 else {
321 nt_free_stack_chunks = ch->prev_free_chunk;
322 ch->prev_free_chunk = NULL;
323 goto retry;
324 }
325 }
326 else {
327 struct nt_stack_chunk_header *p = nt_alloc_thread_stack_chunk();
328 if (p == NULL) {
329 err = errno;
330 }
331 else {
332 nt_free_stack_chunks = nt_stack_chunks = p;
333 goto retry;
334 }
335 }
336 }
337 rb_native_mutex_unlock(&nt_machine_stack_lock);
338
339 return err;
340}
341
342static void
343nt_madvise_free_or_dontneed(void *addr, size_t len)
344{
345 /* There is no real way to perform error handling here. Both MADV_FREE
346 * and MADV_DONTNEED are both documented to pretty much only return EINVAL
347 * for a huge variety of errors. It's indistinguishable if madvise fails
348 * because the parameters were bad, or because the kernel we're running on
349 * does not support the given advice. This kind of free-but-don't-unmap
350 * is best-effort anyway, so don't sweat it.
351 *
352 * n.b. A very common case of "the kernel doesn't support MADV_FREE and
353 * returns EINVAL" is running under the `rr` debugger; it makes all
354 * MADV_FREE calls return EINVAL. */
355
356#if defined(MADV_FREE)
357 int r = madvise(addr, len, MADV_FREE);
358 // Return on success, or else try MADV_DONTNEED
359 if (r == 0) return;
360#endif
361#if defined(MADV_DONTNEED)
362 madvise(addr, len, MADV_DONTNEED);
363#endif
364}
365
366static void
367nt_free_stack(void *mstack)
368{
369 if (!mstack) return;
370
371 rb_native_mutex_lock(&nt_machine_stack_lock);
372 {
373 struct nt_machine_stack_footer *msf = nt_stack_chunk_get_msf(GET_VM(), mstack);
374 struct nt_stack_chunk_header *ch = msf->ch;
375 int idx = (int)msf->index;
376 void *stack = nt_stack_chunk_get_stack_start(ch, idx);
377
378 RUBY_DEBUG_LOG("stack:%p mstack:%p ch:%p index:%d", stack, mstack, ch, idx);
379
380 if (ch->prev_free_chunk == NULL) {
381 ch->prev_free_chunk = nt_free_stack_chunks;
382 nt_free_stack_chunks = ch;
383 }
384 ch->free_stack[ch->free_stack_pos++] = idx;
385
386 // clear the stack pages
387 nt_madvise_free_or_dontneed(stack, nt_thread_stack_size());
388 }
389 rb_native_mutex_unlock(&nt_machine_stack_lock);
390}
391
392
393static int
394native_thread_check_and_create_shared(rb_vm_t *vm)
395{
396 bool need_to_make = false;
397
398 rb_native_mutex_lock(&vm->ractor.sched.lock);
399 {
400 unsigned int snt_cnt = vm->ractor.sched.snt_cnt;
401 if (!vm->ractor.main_ractor->threads.sched.enable_mn_threads) snt_cnt++; // do not need snt for main ractor
402
403 if (((int)snt_cnt < MINIMUM_SNT) ||
404 (snt_cnt < vm->ractor.cnt &&
405 snt_cnt < vm->ractor.sched.max_cpu)) {
406
407 RUBY_DEBUG_LOG("added snt:%u dnt:%u ractor_cnt:%u grq_cnt:%u",
408 vm->ractor.sched.snt_cnt,
409 vm->ractor.sched.dnt_cnt,
410 vm->ractor.cnt,
411 vm->ractor.sched.grq_cnt);
412
413 vm->ractor.sched.snt_cnt++;
414 need_to_make = true;
415 }
416 else {
417 RUBY_DEBUG_LOG("snt:%d ractor_cnt:%d", (int)vm->ractor.sched.snt_cnt, (int)vm->ractor.cnt);
418 }
419 }
420 rb_native_mutex_unlock(&vm->ractor.sched.lock);
421
422 if (need_to_make) {
423 struct rb_native_thread *nt = native_thread_alloc();
424 nt->vm = vm;
425 return native_thread_create0(nt);
426 }
427 else {
428 return 0;
429 }
430}
431
432#ifdef __APPLE__
433# define co_start ruby_coroutine_start
434#else
435static
436#endif
437COROUTINE
438co_start(struct coroutine_context *from, struct coroutine_context *self)
439{
440#ifdef RUBY_ASAN_ENABLED
441 __sanitizer_finish_switch_fiber(self->fake_stack,
442 (const void**)&from->stack_base, &from->stack_size);
443#endif
444
445 rb_thread_t *th = (rb_thread_t *)self->argument;
446 struct rb_thread_sched *sched = TH_SCHED(th);
447 VM_ASSERT(th->nt != NULL);
448 VM_ASSERT(th == sched->running);
449 VM_ASSERT(sched->lock_owner == NULL);
450
451 // RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
452
453 thread_sched_set_locked(sched, th);
454 thread_sched_add_running_thread(TH_SCHED(th), th);
455 thread_sched_unlock(sched, th);
456 {
457 RB_INTERNAL_THREAD_HOOK(RUBY_INTERNAL_THREAD_EVENT_RESUMED, th);
458 call_thread_start_func_2(th);
459 }
460 thread_sched_lock(sched, NULL);
461
462 RUBY_DEBUG_LOG("terminated th:%d", (int)th->serial);
463
464 // Thread is terminated
465
466 struct rb_native_thread *nt = th->nt;
467 bool is_dnt = th_has_dedicated_nt(th);
468 native_thread_assign(NULL, th);
469 rb_ractor_set_current_ec(th->ractor, NULL);
470
471 if (is_dnt) {
472 // SNT became DNT while running. Just return to the nt_context
473
474 th->sched.finished = true;
475 coroutine_transfer0(self, nt->nt_context, true);
476 }
477 else {
478 rb_thread_t *next_th = sched->running;
479
480 if (next_th && !next_th->nt) {
481 // switch to the next thread
482 thread_sched_set_unlocked(sched, NULL);
483 th->sched.finished = true;
484 thread_sched_switch0(th->sched.context, next_th, nt, true);
485 }
486 else {
487 // switch to the next Ractor
488 th->sched.finished = true;
489 coroutine_transfer0(self, nt->nt_context, true);
490 }
491 }
492
493 rb_bug("unreachable");
494}
495
496static int
497native_thread_create_shared(rb_thread_t *th)
498{
499 // setup coroutine
500 rb_vm_t *vm = th->vm;
501 void *vm_stack = NULL, *machine_stack = NULL;
502 int err = nt_alloc_stack(vm, &vm_stack, &machine_stack);
503 if (err) return err;
504
505 VM_ASSERT(vm_stack < machine_stack);
506
507 // setup vm stack
508 size_t vm_stack_words = th->vm->default_params.thread_vm_stack_size/sizeof(VALUE);
509 rb_ec_initialize_vm_stack(th->ec, vm_stack, vm_stack_words);
510
511 // setup machine stack
512 size_t machine_stack_size = vm->default_params.thread_machine_stack_size - sizeof(struct nt_machine_stack_footer);
513 th->ec->machine.stack_start = (void *)((uintptr_t)machine_stack + machine_stack_size);
514 th->ec->machine.stack_maxsize = machine_stack_size; // TODO
515 th->sched.context_stack = machine_stack;
516
517 th->sched.context = ruby_xmalloc(sizeof(struct coroutine_context));
518 coroutine_initialize(th->sched.context, co_start, machine_stack, machine_stack_size);
519 th->sched.context->argument = th;
520
521 RUBY_DEBUG_LOG("th:%u vm_stack:%p machine_stack:%p", rb_th_serial(th), vm_stack, machine_stack);
522 thread_sched_to_ready(TH_SCHED(th), th);
523
524 // setup nt
525 return native_thread_check_and_create_shared(th->vm);
526}
527
528#else // USE_MN_THREADS
529
530static int
531native_thread_create_shared(rb_thread_t *th)
532{
533 rb_bug("unreachable");
534}
535
536static bool
537thread_sched_wait_events(struct rb_thread_sched *sched, rb_thread_t *th, int fd, enum thread_sched_waiting_flag events, rb_hrtime_t *rel)
538{
539 rb_bug("unreachable");
540}
541
542#endif // USE_MN_THREADS
543
545#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
546
547static bool
548fd_readable_nonblock(int fd)
549{
550 struct pollfd pfd = {
551 .fd = fd,
552 .events = POLLIN,
553 };
554 return poll(&pfd, 1, 0) != 0;
555}
556
557static bool
558fd_writable_nonblock(int fd)
559{
560 struct pollfd pfd = {
561 .fd = fd,
562 .events = POLLOUT,
563 };
564 return poll(&pfd, 1, 0) != 0;
565}
566
567static void
568verify_waiting_list(void)
569{
570#if VM_CHECK_MODE > 0
571 struct rb_thread_sched_waiting *w, *prev_w = NULL;
572
573 // waiting list's timeout order should be [1, 2, 3, ..., 0, 0, 0]
574
575 ccan_list_for_each(&timer_th.waiting, w, node) {
576 // fprintf(stderr, "verify_waiting_list th:%u abs:%lu\n", rb_th_serial(wth), (unsigned long)wth->sched.waiting_reason.data.timeout);
577 if (prev_w) {
578 rb_hrtime_t timeout = w->data.timeout;
579 rb_hrtime_t prev_timeout = w->data.timeout;
580 VM_ASSERT(timeout == 0 || prev_timeout <= timeout);
581 }
582 prev_w = w;
583 }
584#endif
585}
586
587#if HAVE_SYS_EVENT_H // kqueue helpers
588
589static enum thread_sched_waiting_flag
590kqueue_translate_filter_to_flags(int16_t filter)
591{
592 switch (filter) {
593 case EVFILT_READ:
594 return thread_sched_waiting_io_read;
595 case EVFILT_WRITE:
596 return thread_sched_waiting_io_write;
597 case EVFILT_TIMER:
598 return thread_sched_waiting_timeout;
599 default:
600 rb_bug("kevent filter:%d not supported", filter);
601 }
602}
603
604static int
605kqueue_wait(rb_vm_t *vm)
606{
607 struct timespec calculated_timeout;
608 struct timespec *timeout = NULL;
609 int timeout_ms = timer_thread_set_timeout(vm);
610
611 if (timeout_ms >= 0) {
612 calculated_timeout.tv_sec = timeout_ms / 1000;
613 calculated_timeout.tv_nsec = (timeout_ms % 1000) * 1000000;
614 timeout = &calculated_timeout;
615 }
616
617 return kevent(timer_th.event_fd, NULL, 0, timer_th.finished_events, KQUEUE_EVENTS_MAX, timeout);
618}
619
620static void
621kqueue_create(void)
622{
623 if ((timer_th.event_fd = kqueue()) == -1) rb_bug("kqueue creation failed (errno:%d)", errno);
624 int flags = fcntl(timer_th.event_fd, F_GETFD);
625 if (flags == -1) {
626 rb_bug("kqueue GETFD failed (errno:%d)", errno);
627 }
628
629 flags |= FD_CLOEXEC;
630 if (fcntl(timer_th.event_fd, F_SETFD, flags) == -1) {
631 rb_bug("kqueue SETFD failed (errno:%d)", errno);
632 }
633}
634
635static void
636kqueue_unregister_waiting(int fd, enum thread_sched_waiting_flag flags)
637{
638 if (flags) {
639 struct kevent ke[2];
640 int num_events = 0;
641
642 if (flags & thread_sched_waiting_io_read) {
643 EV_SET(&ke[num_events], fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
644 num_events++;
645 }
646 if (flags & thread_sched_waiting_io_write) {
647 EV_SET(&ke[num_events], fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
648 num_events++;
649 }
650 if (kevent(timer_th.event_fd, ke, num_events, NULL, 0, NULL) == -1) {
651 perror("kevent");
652 rb_bug("unregister/kevent fails. errno:%d", errno);
653 }
654 }
655}
656
657static bool
658kqueue_already_registered(int fd)
659{
660 struct rb_thread_sched_waiting *w, *found_w = NULL;
661
662 ccan_list_for_each(&timer_th.waiting, w, node) {
663 // Similar to EEXIST in epoll_ctl, but more strict because it checks fd rather than flags
664 // for simplicity
665 if (w->flags && w->data.fd == fd) {
666 found_w = w;
667 break;
668 }
669 }
670 return found_w != NULL;
671}
672
673#endif // HAVE_SYS_EVENT_H
674
675// return false if the fd is not waitable or not need to wait.
676static bool
677timer_thread_register_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags, rb_hrtime_t *rel)
678{
679 RUBY_DEBUG_LOG("th:%u fd:%d flag:%d rel:%lu", rb_th_serial(th), fd, flags, rel ? (unsigned long)*rel : 0);
680
681 VM_ASSERT(th == NULL || TH_SCHED(th)->running == th);
682 VM_ASSERT(flags != 0);
683
684 rb_hrtime_t abs = 0; // 0 means no timeout
685
686 if (rel) {
687 if (*rel > 0) {
688 flags |= thread_sched_waiting_timeout;
689 }
690 else {
691 return false;
692 }
693 }
694
695 if (rel && *rel > 0) {
696 flags |= thread_sched_waiting_timeout;
697 }
698
699#if HAVE_SYS_EVENT_H
700 struct kevent ke[2];
701 int num_events = 0;
702#else
703 uint32_t epoll_events = 0;
704#endif
705 if (flags & thread_sched_waiting_timeout) {
706 VM_ASSERT(rel != NULL);
707 abs = rb_hrtime_add(rb_hrtime_now(), *rel);
708 }
709
710 if (flags & thread_sched_waiting_io_read) {
711 if (!(flags & thread_sched_waiting_io_force) && fd_readable_nonblock(fd)) {
712 RUBY_DEBUG_LOG("fd_readable_nonblock");
713 return false;
714 }
715 else {
716 VM_ASSERT(fd >= 0);
717#if HAVE_SYS_EVENT_H
718 EV_SET(&ke[num_events], fd, EVFILT_READ, EV_ADD, 0, 0, (void *)th);
719 num_events++;
720#else
721 epoll_events |= EPOLLIN;
722#endif
723 }
724 }
725
726 if (flags & thread_sched_waiting_io_write) {
727 if (!(flags & thread_sched_waiting_io_force) && fd_writable_nonblock(fd)) {
728 RUBY_DEBUG_LOG("fd_writable_nonblock");
729 return false;
730 }
731 else {
732 VM_ASSERT(fd >= 0);
733#if HAVE_SYS_EVENT_H
734 EV_SET(&ke[num_events], fd, EVFILT_WRITE, EV_ADD, 0, 0, (void *)th);
735 num_events++;
736#else
737 epoll_events |= EPOLLOUT;
738#endif
739 }
740 }
741
742 rb_native_mutex_lock(&timer_th.waiting_lock);
743 {
744#if HAVE_SYS_EVENT_H
745 if (num_events > 0) {
746 if (kqueue_already_registered(fd)) {
747 rb_native_mutex_unlock(&timer_th.waiting_lock);
748 return false;
749 }
750
751 if (kevent(timer_th.event_fd, ke, num_events, NULL, 0, NULL) == -1) {
752 RUBY_DEBUG_LOG("failed (%d)", errno);
753
754 switch (errno) {
755 case EBADF:
756 // the fd is closed?
757 case EINTR:
758 // signal received? is there a sensible way to handle this?
759 default:
760 perror("kevent");
761 rb_bug("register/kevent failed(fd:%d, errno:%d)", fd, errno);
762 }
763 }
764 RUBY_DEBUG_LOG("kevent(add, fd:%d) success", fd);
765 }
766#else
767 if (epoll_events) {
768 struct epoll_event event = {
769 .events = epoll_events,
770 .data = {
771 .ptr = (void *)th,
772 },
773 };
774 if (epoll_ctl(timer_th.event_fd, EPOLL_CTL_ADD, fd, &event) == -1) {
775 RUBY_DEBUG_LOG("failed (%d)", errno);
776
777 switch (errno) {
778 case EBADF:
779 // the fd is closed?
780 case EPERM:
781 // the fd doesn't support epoll
782 case EEXIST:
783 // the fd is already registered by another thread
784 rb_native_mutex_unlock(&timer_th.waiting_lock);
785 return false;
786 default:
787 perror("epoll_ctl");
788 rb_bug("register/epoll_ctl failed(fd:%d, errno:%d)", fd, errno);
789 }
790 }
791 RUBY_DEBUG_LOG("epoll_ctl(add, fd:%d, events:%d) success", fd, epoll_events);
792 }
793#endif
794
795 if (th) {
796 VM_ASSERT(th->sched.waiting_reason.flags == thread_sched_waiting_none);
797
798 // setup waiting information
799 {
800 th->sched.waiting_reason.flags = flags;
801 th->sched.waiting_reason.data.timeout = abs;
802 th->sched.waiting_reason.data.fd = fd;
803 th->sched.waiting_reason.data.result = 0;
804 }
805
806 if (abs == 0) { // no timeout
807 VM_ASSERT(!(flags & thread_sched_waiting_timeout));
808 ccan_list_add_tail(&timer_th.waiting, &th->sched.waiting_reason.node);
809 }
810 else {
811 RUBY_DEBUG_LOG("abs:%lu", (unsigned long)abs);
812 VM_ASSERT(flags & thread_sched_waiting_timeout);
813
814 // insert th to sorted list (TODO: O(n))
815 struct rb_thread_sched_waiting *w, *prev_w = NULL;
816
817 ccan_list_for_each(&timer_th.waiting, w, node) {
818 if ((w->flags & thread_sched_waiting_timeout) &&
819 w->data.timeout < abs) {
820 prev_w = w;
821 }
822 else {
823 break;
824 }
825 }
826
827 if (prev_w) {
828 ccan_list_add_after(&timer_th.waiting, &prev_w->node, &th->sched.waiting_reason.node);
829 }
830 else {
831 ccan_list_add(&timer_th.waiting, &th->sched.waiting_reason.node);
832 }
833
834 verify_waiting_list();
835
836 // update timeout seconds
837 timer_thread_wakeup();
838 }
839 }
840 else {
841 VM_ASSERT(abs == 0);
842 }
843 }
844 rb_native_mutex_unlock(&timer_th.waiting_lock);
845
846 return true;
847}
848
849static void
850timer_thread_unregister_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags)
851{
852 RUBY_DEBUG_LOG("th:%u fd:%d", rb_th_serial(th), fd);
853#if HAVE_SYS_EVENT_H
854 kqueue_unregister_waiting(fd, flags);
855#else
856 // Linux 2.6.9 or later is needed to pass NULL as data.
857 if (epoll_ctl(timer_th.event_fd, EPOLL_CTL_DEL, fd, NULL) == -1) {
858 switch (errno) {
859 case EBADF:
860 // just ignore. maybe fd is closed.
861 break;
862 default:
863 perror("epoll_ctl");
864 rb_bug("unregister/epoll_ctl fails. errno:%d", errno);
865 }
866 }
867#endif
868}
869
870static void
871timer_thread_setup_mn(void)
872{
873#if HAVE_SYS_EVENT_H
874 kqueue_create();
875 RUBY_DEBUG_LOG("kqueue_fd:%d", timer_th.event_fd);
876#else
877 if ((timer_th.event_fd = epoll_create1(EPOLL_CLOEXEC)) == -1) rb_bug("epoll_create (errno:%d)", errno);
878 RUBY_DEBUG_LOG("epoll_fd:%d", timer_th.event_fd);
879#endif
880 RUBY_DEBUG_LOG("comm_fds:%d/%d", timer_th.comm_fds[0], timer_th.comm_fds[1]);
881
882 timer_thread_register_waiting(NULL, timer_th.comm_fds[0], thread_sched_waiting_io_read | thread_sched_waiting_io_force, NULL);
883}
884
885static int
886event_wait(rb_vm_t *vm)
887{
888#if HAVE_SYS_EVENT_H
889 int r = kqueue_wait(vm);
890#else
891 int r = epoll_wait(timer_th.event_fd, timer_th.finished_events, EPOLL_EVENTS_MAX, timer_thread_set_timeout(vm));
892#endif
893 return r;
894}
895
896/*
897 * The purpose of the timer thread:
898 *
899 * (1) Periodic checking
900 * (1-1) Provide time slice for active NTs
901 * (1-2) Check NT shortage
902 * (1-3) Periodic UBF (global)
903 * (1-4) Lazy GRQ deq start
904 * (2) Receive notification
905 * (2-1) async I/O termination
906 * (2-2) timeout
907 * (2-2-1) sleep(n)
908 * (2-2-2) timeout(n), I/O, ...
909 */
910static void
911timer_thread_polling(rb_vm_t *vm)
912{
913 int r = event_wait(vm);
914
915 RUBY_DEBUG_LOG("r:%d errno:%d", r, errno);
916
917 switch (r) {
918 case 0: // timeout
919 RUBY_DEBUG_LOG("timeout%s", "");
920
921 ractor_sched_lock(vm, NULL);
922 {
923 // (1-1) timeslice
924 timer_thread_check_timeslice(vm);
925
926 // (1-4) lazy grq deq
927 if (vm->ractor.sched.grq_cnt > 0) {
928 RUBY_DEBUG_LOG("GRQ cnt: %u", vm->ractor.sched.grq_cnt);
929 rb_native_cond_signal(&vm->ractor.sched.cond);
930 }
931 }
932 ractor_sched_unlock(vm, NULL);
933
934 // (1-2)
935 native_thread_check_and_create_shared(vm);
936
937 break;
938
939 case -1:
940 switch (errno) {
941 case EINTR:
942 // simply retry
943 break;
944 default:
945 perror("event_wait");
946 rb_bug("event_wait errno:%d", errno);
947 }
948 break;
949
950 default:
951 RUBY_DEBUG_LOG("%d event(s)", r);
952
953#if HAVE_SYS_EVENT_H
954 for (int i=0; i<r; i++) {
955 rb_thread_t *th = (rb_thread_t *)timer_th.finished_events[i].udata;
956 int fd = (int)timer_th.finished_events[i].ident;
957 int16_t filter = timer_th.finished_events[i].filter;
958
959 if (th == NULL) {
960 // wakeup timerthread
961 RUBY_DEBUG_LOG("comm from fd:%d", timer_th.comm_fds[1]);
962 consume_communication_pipe(timer_th.comm_fds[0]);
963 }
964 else {
965 // wakeup specific thread by IO
966 RUBY_DEBUG_LOG("io event. wakeup_th:%u event:%s%s",
967 rb_th_serial(th),
968 (filter == EVFILT_READ) ? "read/" : "",
969 (filter == EVFILT_WRITE) ? "write/" : "");
970
971 rb_native_mutex_lock(&timer_th.waiting_lock);
972 {
973 if (th->sched.waiting_reason.flags) {
974 // delete from chain
975 ccan_list_del_init(&th->sched.waiting_reason.node);
976 timer_thread_unregister_waiting(th, fd, kqueue_translate_filter_to_flags(filter));
977
978 th->sched.waiting_reason.flags = thread_sched_waiting_none;
979 th->sched.waiting_reason.data.fd = -1;
980 th->sched.waiting_reason.data.result = filter;
981
982 timer_thread_wakeup_thread(th);
983 }
984 else {
985 // already released
986 }
987 }
988 rb_native_mutex_unlock(&timer_th.waiting_lock);
989 }
990 }
991#else
992 for (int i=0; i<r; i++) {
993 rb_thread_t *th = (rb_thread_t *)timer_th.finished_events[i].data.ptr;
994
995 if (th == NULL) {
996 // wakeup timerthread
997 RUBY_DEBUG_LOG("comm from fd:%d", timer_th.comm_fds[1]);
998 consume_communication_pipe(timer_th.comm_fds[0]);
999 }
1000 else {
1001 // wakeup specific thread by IO
1002 uint32_t events = timer_th.finished_events[i].events;
1003
1004 RUBY_DEBUG_LOG("io event. wakeup_th:%u event:%s%s%s%s%s%s",
1005 rb_th_serial(th),
1006 (events & EPOLLIN) ? "in/" : "",
1007 (events & EPOLLOUT) ? "out/" : "",
1008 (events & EPOLLRDHUP) ? "RDHUP/" : "",
1009 (events & EPOLLPRI) ? "pri/" : "",
1010 (events & EPOLLERR) ? "err/" : "",
1011 (events & EPOLLHUP) ? "hup/" : "");
1012
1013 rb_native_mutex_lock(&timer_th.waiting_lock);
1014 {
1015 if (th->sched.waiting_reason.flags) {
1016 // delete from chain
1017 ccan_list_del_init(&th->sched.waiting_reason.node);
1018 timer_thread_unregister_waiting(th, th->sched.waiting_reason.data.fd, th->sched.waiting_reason.flags);
1019
1020 th->sched.waiting_reason.flags = thread_sched_waiting_none;
1021 th->sched.waiting_reason.data.fd = -1;
1022 th->sched.waiting_reason.data.result = (int)events;
1023
1024 timer_thread_wakeup_thread(th);
1025 }
1026 else {
1027 // already released
1028 }
1029 }
1030 rb_native_mutex_unlock(&timer_th.waiting_lock);
1031 }
1032 }
1033#endif
1034 }
1035}
1036
1037#else // HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H
1038
1039static void
1040timer_thread_setup_mn(void)
1041{
1042 // do nothing
1043}
1044
1045static void
1046timer_thread_polling(rb_vm_t *vm)
1047{
1048 int timeout = timer_thread_set_timeout(vm);
1049
1050 struct pollfd pfd = {
1051 .fd = timer_th.comm_fds[0],
1052 .events = POLLIN,
1053 };
1054
1055 int r = poll(&pfd, 1, timeout);
1056
1057 switch (r) {
1058 case 0: // timeout
1059 rb_native_mutex_lock(&vm->ractor.sched.lock);
1060 {
1061 // (1-1) timeslice
1062 timer_thread_check_timeslice(vm);
1063 }
1064 rb_native_mutex_unlock(&vm->ractor.sched.lock);
1065 break;
1066
1067 case -1: // error
1068 switch (errno) {
1069 case EINTR:
1070 // simply retry
1071 break;
1072 default:
1073 perror("poll");
1074 rb_bug("poll errno:%d", errno);
1075 break;
1076 }
1077
1078 case 1:
1079 consume_communication_pipe(timer_th.comm_fds[0]);
1080 break;
1081
1082 default:
1083 rb_bug("unreachbale");
1084 }
1085}
1086
1087#endif // HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H
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:238
#define RUBY_INTERNAL_THREAD_EVENT_SUSPENDED
Triggered when a thread released the GVL.
Definition thread.h:245
#define RBIMPL_ATTR_MAYBE_UNUSED()
Wraps (or simulates) [[maybe_unused]]
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_cond_signal(rb_nativethread_cond_t *cond)
Signals a condition variable.
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40