Ruby 3.5.0dev (2025-04-11 revision 0a35c5b4d9add69251590e3902a5d861df49e142)
thread_pthread_mn.c (0a35c5b4d9add69251590e3902a5d861df49e142)
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 setup_ubf(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 setup_ubf(th, NULL, NULL); // 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_lock_owner(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_vm_t *vm = th->vm;
479 bool has_ready_ractor = vm->ractor.sched.grq_cnt > 0; // at least this ractor is not queued
480 rb_thread_t *next_th = sched->running;
481
482 if (!has_ready_ractor && next_th && !next_th->nt) {
483 // switch to the next thread
484 thread_sched_set_lock_owner(sched, NULL);
485 th->sched.finished = true;
486 thread_sched_switch0(th->sched.context, next_th, nt, true);
487 }
488 else {
489 // switch to the next Ractor
490 th->sched.finished = true;
491 coroutine_transfer0(self, nt->nt_context, true);
492 }
493 }
494
495 rb_bug("unreachable");
496}
497
498static int
499native_thread_create_shared(rb_thread_t *th)
500{
501 // setup coroutine
502 rb_vm_t *vm = th->vm;
503 void *vm_stack = NULL, *machine_stack = NULL;
504 int err = nt_alloc_stack(vm, &vm_stack, &machine_stack);
505 if (err) return err;
506
507 VM_ASSERT(vm_stack < machine_stack);
508
509 // setup vm stack
510 size_t vm_stack_words = th->vm->default_params.thread_vm_stack_size/sizeof(VALUE);
511 rb_ec_initialize_vm_stack(th->ec, vm_stack, vm_stack_words);
512
513 // setup machine stack
514 size_t machine_stack_size = vm->default_params.thread_machine_stack_size - sizeof(struct nt_machine_stack_footer);
515 th->ec->machine.stack_start = (void *)((uintptr_t)machine_stack + machine_stack_size);
516 th->ec->machine.stack_maxsize = machine_stack_size; // TODO
517 th->sched.context_stack = machine_stack;
518
519 th->sched.context = ruby_xmalloc(sizeof(struct coroutine_context));
520 coroutine_initialize(th->sched.context, co_start, machine_stack, machine_stack_size);
521 th->sched.context->argument = th;
522
523 RUBY_DEBUG_LOG("th:%u vm_stack:%p machine_stack:%p", rb_th_serial(th), vm_stack, machine_stack);
524 thread_sched_to_ready(TH_SCHED(th), th);
525
526 // setup nt
527 return native_thread_check_and_create_shared(th->vm);
528}
529
530#else // USE_MN_THREADS
531
532static int
533native_thread_create_shared(rb_thread_t *th)
534{
535 rb_bug("unreachable");
536}
537
538static bool
539thread_sched_wait_events(struct rb_thread_sched *sched, rb_thread_t *th, int fd, enum thread_sched_waiting_flag events, rb_hrtime_t *rel)
540{
541 rb_bug("unreachable");
542}
543
544#endif // USE_MN_THREADS
545
547#if (HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H) && USE_MN_THREADS
548
549static bool
550fd_readable_nonblock(int fd)
551{
552 struct pollfd pfd = {
553 .fd = fd,
554 .events = POLLIN,
555 };
556 return poll(&pfd, 1, 0) != 0;
557}
558
559static bool
560fd_writable_nonblock(int fd)
561{
562 struct pollfd pfd = {
563 .fd = fd,
564 .events = POLLOUT,
565 };
566 return poll(&pfd, 1, 0) != 0;
567}
568
569static void
570verify_waiting_list(void)
571{
572#if VM_CHECK_MODE > 0
573 struct rb_thread_sched_waiting *w, *prev_w = NULL;
574
575 // waiting list's timeout order should be [1, 2, 3, ..., 0, 0, 0]
576
577 ccan_list_for_each(&timer_th.waiting, w, node) {
578 // fprintf(stderr, "verify_waiting_list th:%u abs:%lu\n", rb_th_serial(wth), (unsigned long)wth->sched.waiting_reason.data.timeout);
579 if (prev_w) {
580 rb_hrtime_t timeout = w->data.timeout;
581 rb_hrtime_t prev_timeout = w->data.timeout;
582 VM_ASSERT(timeout == 0 || prev_timeout <= timeout);
583 }
584 prev_w = w;
585 }
586#endif
587}
588
589#if HAVE_SYS_EVENT_H // kqueue helpers
590
591static enum thread_sched_waiting_flag
592kqueue_translate_filter_to_flags(int16_t filter)
593{
594 switch (filter) {
595 case EVFILT_READ:
596 return thread_sched_waiting_io_read;
597 case EVFILT_WRITE:
598 return thread_sched_waiting_io_write;
599 case EVFILT_TIMER:
600 return thread_sched_waiting_timeout;
601 default:
602 rb_bug("kevent filter:%d not supported", filter);
603 }
604}
605
606static int
607kqueue_wait(rb_vm_t *vm)
608{
609 struct timespec calculated_timeout;
610 struct timespec *timeout = NULL;
611 int timeout_ms = timer_thread_set_timeout(vm);
612
613 if (timeout_ms >= 0) {
614 calculated_timeout.tv_sec = timeout_ms / 1000;
615 calculated_timeout.tv_nsec = (timeout_ms % 1000) * 1000000;
616 timeout = &calculated_timeout;
617 }
618
619 return kevent(timer_th.event_fd, NULL, 0, timer_th.finished_events, KQUEUE_EVENTS_MAX, timeout);
620}
621
622static void
623kqueue_create(void)
624{
625 if ((timer_th.event_fd = kqueue()) == -1) rb_bug("kqueue creation failed (errno:%d)", errno);
626 int flags = fcntl(timer_th.event_fd, F_GETFD);
627 if (flags == -1) {
628 rb_bug("kqueue GETFD failed (errno:%d)", errno);
629 }
630
631 flags |= FD_CLOEXEC;
632 if (fcntl(timer_th.event_fd, F_SETFD, flags) == -1) {
633 rb_bug("kqueue SETFD failed (errno:%d)", errno);
634 }
635}
636
637static void
638kqueue_unregister_waiting(int fd, enum thread_sched_waiting_flag flags)
639{
640 if (flags) {
641 struct kevent ke[2];
642 int num_events = 0;
643
644 if (flags & thread_sched_waiting_io_read) {
645 EV_SET(&ke[num_events], fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
646 num_events++;
647 }
648 if (flags & thread_sched_waiting_io_write) {
649 EV_SET(&ke[num_events], fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
650 num_events++;
651 }
652 if (kevent(timer_th.event_fd, ke, num_events, NULL, 0, NULL) == -1) {
653 perror("kevent");
654 rb_bug("unregister/kevent fails. errno:%d", errno);
655 }
656 }
657}
658
659static bool
660kqueue_already_registered(int fd)
661{
662 struct rb_thread_sched_waiting *w, *found_w = NULL;
663
664 ccan_list_for_each(&timer_th.waiting, w, node) {
665 // Similar to EEXIST in epoll_ctl, but more strict because it checks fd rather than flags
666 // for simplicity
667 if (w->flags && w->data.fd == fd) {
668 found_w = w;
669 break;
670 }
671 }
672 return found_w != NULL;
673}
674
675#endif // HAVE_SYS_EVENT_H
676
677// return false if the fd is not waitable or not need to wait.
678static bool
679timer_thread_register_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags, rb_hrtime_t *rel)
680{
681 RUBY_DEBUG_LOG("th:%u fd:%d flag:%d rel:%lu", rb_th_serial(th), fd, flags, rel ? (unsigned long)*rel : 0);
682
683 VM_ASSERT(th == NULL || TH_SCHED(th)->running == th);
684 VM_ASSERT(flags != 0);
685
686 rb_hrtime_t abs = 0; // 0 means no timeout
687
688 if (rel) {
689 if (*rel > 0) {
690 flags |= thread_sched_waiting_timeout;
691 }
692 else {
693 return false;
694 }
695 }
696
697 if (rel && *rel > 0) {
698 flags |= thread_sched_waiting_timeout;
699 }
700
701#if HAVE_SYS_EVENT_H
702 struct kevent ke[2];
703 int num_events = 0;
704#else
705 uint32_t epoll_events = 0;
706#endif
707 if (flags & thread_sched_waiting_timeout) {
708 VM_ASSERT(rel != NULL);
709 abs = rb_hrtime_add(rb_hrtime_now(), *rel);
710 }
711
712 if (flags & thread_sched_waiting_io_read) {
713 if (!(flags & thread_sched_waiting_io_force) && fd_readable_nonblock(fd)) {
714 RUBY_DEBUG_LOG("fd_readable_nonblock");
715 return false;
716 }
717 else {
718 VM_ASSERT(fd >= 0);
719#if HAVE_SYS_EVENT_H
720 EV_SET(&ke[num_events], fd, EVFILT_READ, EV_ADD, 0, 0, (void *)th);
721 num_events++;
722#else
723 epoll_events |= EPOLLIN;
724#endif
725 }
726 }
727
728 if (flags & thread_sched_waiting_io_write) {
729 if (!(flags & thread_sched_waiting_io_force) && fd_writable_nonblock(fd)) {
730 RUBY_DEBUG_LOG("fd_writable_nonblock");
731 return false;
732 }
733 else {
734 VM_ASSERT(fd >= 0);
735#if HAVE_SYS_EVENT_H
736 EV_SET(&ke[num_events], fd, EVFILT_WRITE, EV_ADD, 0, 0, (void *)th);
737 num_events++;
738#else
739 epoll_events |= EPOLLOUT;
740#endif
741 }
742 }
743
744 rb_native_mutex_lock(&timer_th.waiting_lock);
745 {
746#if HAVE_SYS_EVENT_H
747 if (num_events > 0) {
748 if (kqueue_already_registered(fd)) {
749 rb_native_mutex_unlock(&timer_th.waiting_lock);
750 return false;
751 }
752
753 if (kevent(timer_th.event_fd, ke, num_events, NULL, 0, NULL) == -1) {
754 RUBY_DEBUG_LOG("failed (%d)", errno);
755
756 switch (errno) {
757 case EBADF:
758 // the fd is closed?
759 case EINTR:
760 // signal received? is there a sensible way to handle this?
761 default:
762 perror("kevent");
763 rb_bug("register/kevent failed(fd:%d, errno:%d)", fd, errno);
764 }
765 }
766 RUBY_DEBUG_LOG("kevent(add, fd:%d) success", fd);
767 }
768#else
769 if (epoll_events) {
770 struct epoll_event event = {
771 .events = epoll_events,
772 .data = {
773 .ptr = (void *)th,
774 },
775 };
776 if (epoll_ctl(timer_th.event_fd, EPOLL_CTL_ADD, fd, &event) == -1) {
777 RUBY_DEBUG_LOG("failed (%d)", errno);
778
779 switch (errno) {
780 case EBADF:
781 // the fd is closed?
782 case EPERM:
783 // the fd doesn't support epoll
784 case EEXIST:
785 // the fd is already registered by another thread
786 rb_native_mutex_unlock(&timer_th.waiting_lock);
787 return false;
788 default:
789 perror("epoll_ctl");
790 rb_bug("register/epoll_ctl failed(fd:%d, errno:%d)", fd, errno);
791 }
792 }
793 RUBY_DEBUG_LOG("epoll_ctl(add, fd:%d, events:%d) success", fd, epoll_events);
794 }
795#endif
796
797 if (th) {
798 VM_ASSERT(th->sched.waiting_reason.flags == thread_sched_waiting_none);
799
800 // setup waiting information
801 {
802 th->sched.waiting_reason.flags = flags;
803 th->sched.waiting_reason.data.timeout = abs;
804 th->sched.waiting_reason.data.fd = fd;
805 th->sched.waiting_reason.data.result = 0;
806 }
807
808 if (abs == 0) { // no timeout
809 VM_ASSERT(!(flags & thread_sched_waiting_timeout));
810 ccan_list_add_tail(&timer_th.waiting, &th->sched.waiting_reason.node);
811 }
812 else {
813 RUBY_DEBUG_LOG("abs:%lu", (unsigned long)abs);
814 VM_ASSERT(flags & thread_sched_waiting_timeout);
815
816 // insert th to sorted list (TODO: O(n))
817 struct rb_thread_sched_waiting *w, *prev_w = NULL;
818
819 ccan_list_for_each(&timer_th.waiting, w, node) {
820 if ((w->flags & thread_sched_waiting_timeout) &&
821 w->data.timeout < abs) {
822 prev_w = w;
823 }
824 else {
825 break;
826 }
827 }
828
829 if (prev_w) {
830 ccan_list_add_after(&timer_th.waiting, &prev_w->node, &th->sched.waiting_reason.node);
831 }
832 else {
833 ccan_list_add(&timer_th.waiting, &th->sched.waiting_reason.node);
834 }
835
836 verify_waiting_list();
837
838 // update timeout seconds
839 timer_thread_wakeup();
840 }
841 }
842 else {
843 VM_ASSERT(abs == 0);
844 }
845 }
846 rb_native_mutex_unlock(&timer_th.waiting_lock);
847
848 return true;
849}
850
851static void
852timer_thread_unregister_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags)
853{
854 RUBY_DEBUG_LOG("th:%u fd:%d", rb_th_serial(th), fd);
855#if HAVE_SYS_EVENT_H
856 kqueue_unregister_waiting(fd, flags);
857#else
858 // Linux 2.6.9 or later is needed to pass NULL as data.
859 if (epoll_ctl(timer_th.event_fd, EPOLL_CTL_DEL, fd, NULL) == -1) {
860 switch (errno) {
861 case EBADF:
862 // just ignore. maybe fd is closed.
863 break;
864 default:
865 perror("epoll_ctl");
866 rb_bug("unregister/epoll_ctl fails. errno:%d", errno);
867 }
868 }
869#endif
870}
871
872static void
873timer_thread_setup_mn(void)
874{
875#if HAVE_SYS_EVENT_H
876 kqueue_create();
877 RUBY_DEBUG_LOG("kqueue_fd:%d", timer_th.event_fd);
878#else
879 if ((timer_th.event_fd = epoll_create1(EPOLL_CLOEXEC)) == -1) rb_bug("epoll_create (errno:%d)", errno);
880 RUBY_DEBUG_LOG("epoll_fd:%d", timer_th.event_fd);
881#endif
882 RUBY_DEBUG_LOG("comm_fds:%d/%d", timer_th.comm_fds[0], timer_th.comm_fds[1]);
883
884 timer_thread_register_waiting(NULL, timer_th.comm_fds[0], thread_sched_waiting_io_read | thread_sched_waiting_io_force, NULL);
885}
886
887static int
888event_wait(rb_vm_t *vm)
889{
890#if HAVE_SYS_EVENT_H
891 int r = kqueue_wait(vm);
892#else
893 int r = epoll_wait(timer_th.event_fd, timer_th.finished_events, EPOLL_EVENTS_MAX, timer_thread_set_timeout(vm));
894#endif
895 return r;
896}
897
898/*
899 * The purpose of the timer thread:
900 *
901 * (1) Periodic checking
902 * (1-1) Provide time slice for active NTs
903 * (1-2) Check NT shortage
904 * (1-3) Periodic UBF (global)
905 * (1-4) Lazy GRQ deq start
906 * (2) Receive notification
907 * (2-1) async I/O termination
908 * (2-2) timeout
909 * (2-2-1) sleep(n)
910 * (2-2-2) timeout(n), I/O, ...
911 */
912static void
913timer_thread_polling(rb_vm_t *vm)
914{
915 int r = event_wait(vm);
916
917 RUBY_DEBUG_LOG("r:%d errno:%d", r, errno);
918
919 switch (r) {
920 case 0: // timeout
921 RUBY_DEBUG_LOG("timeout%s", "");
922
923 ractor_sched_lock(vm, NULL);
924 {
925 // (1-1) timeslice
926 timer_thread_check_timeslice(vm);
927
928 // (1-4) lazy grq deq
929 if (vm->ractor.sched.grq_cnt > 0) {
930 RUBY_DEBUG_LOG("GRQ cnt: %u", vm->ractor.sched.grq_cnt);
931 rb_native_cond_signal(&vm->ractor.sched.cond);
932 }
933 }
934 ractor_sched_unlock(vm, NULL);
935
936 // (1-2)
937 native_thread_check_and_create_shared(vm);
938
939 break;
940
941 case -1:
942 switch (errno) {
943 case EINTR:
944 // simply retry
945 break;
946 default:
947 perror("event_wait");
948 rb_bug("event_wait errno:%d", errno);
949 }
950 break;
951
952 default:
953 RUBY_DEBUG_LOG("%d event(s)", r);
954
955#if HAVE_SYS_EVENT_H
956 for (int i=0; i<r; i++) {
957 rb_thread_t *th = (rb_thread_t *)timer_th.finished_events[i].udata;
958 int fd = (int)timer_th.finished_events[i].ident;
959 int16_t filter = timer_th.finished_events[i].filter;
960
961 if (th == NULL) {
962 // wakeup timerthread
963 RUBY_DEBUG_LOG("comm from fd:%d", timer_th.comm_fds[1]);
964 consume_communication_pipe(timer_th.comm_fds[0]);
965 }
966 else {
967 // wakeup specific thread by IO
968 RUBY_DEBUG_LOG("io event. wakeup_th:%u event:%s%s",
969 rb_th_serial(th),
970 (filter == EVFILT_READ) ? "read/" : "",
971 (filter == EVFILT_WRITE) ? "write/" : "");
972
973 rb_native_mutex_lock(&timer_th.waiting_lock);
974 {
975 if (th->sched.waiting_reason.flags) {
976 // delete from chain
977 ccan_list_del_init(&th->sched.waiting_reason.node);
978 timer_thread_unregister_waiting(th, fd, kqueue_translate_filter_to_flags(filter));
979
980 th->sched.waiting_reason.flags = thread_sched_waiting_none;
981 th->sched.waiting_reason.data.fd = -1;
982 th->sched.waiting_reason.data.result = filter;
983
984 timer_thread_wakeup_thread(th);
985 }
986 else {
987 // already released
988 }
989 }
990 rb_native_mutex_unlock(&timer_th.waiting_lock);
991 }
992 }
993#else
994 for (int i=0; i<r; i++) {
995 rb_thread_t *th = (rb_thread_t *)timer_th.finished_events[i].data.ptr;
996
997 if (th == NULL) {
998 // wakeup timerthread
999 RUBY_DEBUG_LOG("comm from fd:%d", timer_th.comm_fds[1]);
1000 consume_communication_pipe(timer_th.comm_fds[0]);
1001 }
1002 else {
1003 // wakeup specific thread by IO
1004 uint32_t events = timer_th.finished_events[i].events;
1005
1006 RUBY_DEBUG_LOG("io event. wakeup_th:%u event:%s%s%s%s%s%s",
1007 rb_th_serial(th),
1008 (events & EPOLLIN) ? "in/" : "",
1009 (events & EPOLLOUT) ? "out/" : "",
1010 (events & EPOLLRDHUP) ? "RDHUP/" : "",
1011 (events & EPOLLPRI) ? "pri/" : "",
1012 (events & EPOLLERR) ? "err/" : "",
1013 (events & EPOLLHUP) ? "hup/" : "");
1014
1015 rb_native_mutex_lock(&timer_th.waiting_lock);
1016 {
1017 if (th->sched.waiting_reason.flags) {
1018 // delete from chain
1019 ccan_list_del_init(&th->sched.waiting_reason.node);
1020 timer_thread_unregister_waiting(th, th->sched.waiting_reason.data.fd, th->sched.waiting_reason.flags);
1021
1022 th->sched.waiting_reason.flags = thread_sched_waiting_none;
1023 th->sched.waiting_reason.data.fd = -1;
1024 th->sched.waiting_reason.data.result = (int)events;
1025
1026 timer_thread_wakeup_thread(th);
1027 }
1028 else {
1029 // already released
1030 }
1031 }
1032 rb_native_mutex_unlock(&timer_th.waiting_lock);
1033 }
1034 }
1035#endif
1036 }
1037}
1038
1039#else // HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H
1040
1041static void
1042timer_thread_setup_mn(void)
1043{
1044 // do nothing
1045}
1046
1047static void
1048timer_thread_polling(rb_vm_t *vm)
1049{
1050 int timeout = timer_thread_set_timeout(vm);
1051
1052 struct pollfd pfd = {
1053 .fd = timer_th.comm_fds[0],
1054 .events = POLLIN,
1055 };
1056
1057 int r = poll(&pfd, 1, timeout);
1058
1059 switch (r) {
1060 case 0: // timeout
1061 rb_native_mutex_lock(&vm->ractor.sched.lock);
1062 {
1063 // (1-1) timeslice
1064 timer_thread_check_timeslice(vm);
1065 }
1066 rb_native_mutex_unlock(&vm->ractor.sched.lock);
1067 break;
1068
1069 case -1: // error
1070 switch (errno) {
1071 case EINTR:
1072 // simply retry
1073 break;
1074 default:
1075 perror("poll");
1076 rb_bug("poll errno:%d", errno);
1077 break;
1078 }
1079
1080 case 1:
1081 consume_communication_pipe(timer_th.comm_fds[0]);
1082 break;
1083
1084 default:
1085 rb_bug("unreachbale");
1086 }
1087}
1088
1089#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