Ruby 4.1.0dev (2026-11-27 revision 0d399335b733776187e43a783e5f950c18ad881c)
thread_sched_mn.c (0d399335b733776187e43a783e5f950c18ad881c)
1/* -*-c-*- */
2/**********************************************************************
3
4 thread_sched_mn.c - the M:N scheduler
5
6 Included by the platform implementation (currently only thread_pthread.c)
7 when USE_MN_THREADS is 1. A platform that cannot run coroutine threads
8 defines it to 0 and supplies the stubs at the bottom of this file itself
9 (see thread_win32.c).
10
11 Most of what is here is platform independent: the coroutine threads
12 themselves, the native thread stack pool, the timer wheel, and the
13 fd -> waiters map. The part that is not is the readiness backend --
14 arming an fd and waiting for events -- which is epoll on Linux and kqueue
15 elsewhere. Those pieces are marked "backend" below; they are the natural
16 seam for a thread_sched_epoll.c / thread_sched_kqueue.c split, and for an
17 IOCP backend that would let Windows run M:N threads too.
18
19**********************************************************************/
20
21#if USE_MN_THREADS
22
23#if HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H
24static void timer_thread_unregister_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags);
25#endif
26
27static bool
28timer_thread_check_exceed(rb_hrtime_t abs, rb_hrtime_t now)
29{
30 return abs <= now;
31}
32
33static rb_thread_t *
34thread_sched_waiting_thread(struct rb_thread_sched_waiting *w)
35{
36 if (w) {
37 return (rb_thread_t *)((size_t)w - offsetof(rb_thread_t, sched.waiting_reason));
38 }
39 else {
40 return NULL;
41 }
42}
43
44#define FD_WAIT_IO_MASK (thread_sched_waiting_io_read | thread_sched_waiting_io_write)
45
46// Guards the fd map entries and the flags of io waits for its fds. Whoever
47// clears an io wait's flags under its shard owns that wakeup.
48// Lock order: shard -> waiting_lock -> wake_pending_lock.
49static void
50fd_shard_lock(int fd)
51{
52 rb_native_mutex_lock(&timer_th.fd_shard_locks[(unsigned int)fd % IO_WAIT_SHARDS]);
53}
54
55static void
56fd_shard_unlock(int fd)
57{
58 rb_native_mutex_unlock(&timer_th.fd_shard_locks[(unsigned int)fd % IO_WAIT_SHARDS]);
59}
60
61#define TIMER_WHEEL_NO_EXPIRY RB_HRTIME_MAX
62#ifndef TIMER_WHEEL_TICK_MS
63#define TIMER_WHEEL_TICK_MS 1 // L0 slot width; coarser trades sleep accuracy for fewer drains
64#endif
65
66/* Timer wheel over the timed waiters. Every operation runs under
67 * timer_th.waiting_lock.
68 *
69 * Level L buckets deadlines into 64 slots of 64^L ms each; a deadline is
70 * placed by its distance from the drain cursor, so its slot is always
71 * strictly ahead of the cursor at that level. The drain refines a
72 * not-yet-due waiter onto a finer level instead of cascading whole slots,
73 * so one waiter moves at most once per level over its lifetime.
74 *
75 * This is the hierarchical timing wheel of Varghese & Lauck, "Hashed and
76 * Hierarchical Timing Wheels" (SOSP '87). */
77
78static uint64_t
79timer_wheel_tick(rb_hrtime_t hrt)
80{
81 return hrt / (RB_HRTIME_PER_MSEC * TIMER_WHEEL_TICK_MS);
82}
83
84static inline int
85timer_wheel_ctz64(uint64_t v)
86{
87#if defined(__GNUC__) || defined(__clang__)
88 return __builtin_ctzll(v);
89#else
90 int n = 0;
91 while (!(v & 1)) { v >>= 1; n++; }
92 return n;
93#endif
94}
95
96static int
97timer_wheel_level(uint64_t dist_ms)
98{
99 if (dist_ms < ((uint64_t)1 << TIMER_WHEEL_SLOT_BITS)) return 0;
100 if (dist_ms < ((uint64_t)1 << 2 * TIMER_WHEEL_SLOT_BITS)) return 1;
101 if (dist_ms < ((uint64_t)1 << 3 * TIMER_WHEEL_SLOT_BITS)) return 2;
102 return TIMER_WHEEL_LEVELS - 1;
103}
104
105static void
106timer_wheel_insert(struct rb_thread_sched_waiting *w)
107{
108 uint64_t dl_tick = timer_wheel_tick(w->data.timeout);
109 uint64_t cur = timer_th.wheel_cursor_tick;
110
111 /* A deadline at or behind the cursor parks one tick ahead: its own slot
112 * is already drained and would otherwise wait out a full wheel turn. */
113 uint64_t target = dl_tick > cur ? dl_tick : cur + 1;
114 int lvl = timer_wheel_level(target - cur);
115 int shift = lvl * TIMER_WHEEL_SLOT_BITS;
116 uint64_t slot_tick = target >> shift;
117
118 if (lvl == TIMER_WHEEL_LEVELS - 1) {
119 /* Beyond the wheel range: park on the farthest slot; the drain
120 * re-inserts it with the then-smaller distance. */
121 uint64_t far = (cur >> shift) + TIMER_WHEEL_SLOTS - 1;
122 if (slot_tick > far) slot_tick = far;
123 }
124
125 int slot = (int)(slot_tick & (TIMER_WHEEL_SLOTS - 1));
126
127 ccan_list_add_tail(&timer_th.wheel[lvl].slots[slot], &w->node);
128 timer_th.wheel[lvl].occupied |= UINT64_C(1) << slot;
129 w->wheel_lvl = (uint8_t)lvl;
130 w->wheel_slot = (uint8_t)slot;
131
132 if (w->data.timeout < timer_th.next_expiry) {
133 timer_th.next_expiry = w->data.timeout;
134 }
135}
136
137// Unlink a waiter from the wheel slot or the untimed list it is on.
138static void
139timer_wheel_del(struct rb_thread_sched_waiting *w)
140{
141 ccan_list_del_init(&w->node);
142
143 if (w->flags & thread_sched_waiting_timeout) {
144 struct timer_wheel_level *lv = &timer_th.wheel[w->wheel_lvl];
145 if (ccan_list_empty(&lv->slots[w->wheel_slot])) {
146 lv->occupied &= ~(UINT64_C(1) << w->wheel_slot);
147 }
148 }
149}
150
151/* A lower bound on the earliest deadline: the start time of the nearest
152 * occupied slot per level. Never later than any real deadline, so waking
153 * by it is at worst early, which is harmless. */
154static rb_hrtime_t
155timer_wheel_next_expiry(void)
156{
157 rb_hrtime_t best = TIMER_WHEEL_NO_EXPIRY;
158
159 for (int lvl = 0; lvl < TIMER_WHEEL_LEVELS; lvl++) {
160 uint64_t occ = timer_th.wheel[lvl].occupied;
161 if (!occ) continue;
162
163 int shift = lvl * TIMER_WHEEL_SLOT_BITS;
164 uint64_t cur_tick = timer_th.wheel_cursor_tick >> shift;
165 unsigned base = (unsigned)((cur_tick + 1) & (TIMER_WHEEL_SLOTS - 1));
166 // rotate so bit k = slot for tick cur_tick+1+k
167 uint64_t rot = (occ >> base) | (base ? (occ << (TIMER_WHEEL_SLOTS - base)) : 0);
168 uint64_t tick = cur_tick + 1 + timer_wheel_ctz64(rot);
169 rb_hrtime_t start = (rb_hrtime_t)(tick << shift) * RB_HRTIME_PER_MSEC * TIMER_WHEEL_TICK_MS;
170
171 if (start < best) best = start;
172 }
173
174 return best;
175}
176
177/* Drain every slot whose tick moved behind `now`, collecting due waiters
178 * onto `expired` and re-bucketing not-yet-due ones onto a finer level.
179 * timer_th.waiting_lock must be held. */
180static void
181timer_wheel_drain(rb_hrtime_t now, uint64_t now_tick, struct ccan_list_head *expired)
182{
183 uint64_t prev_tick = timer_th.wheel_cursor_tick;
184 timer_th.wheel_cursor_tick = now_tick; // re-inserts below map against the new cursor
185 /* A deadline inside the current tick parks one tick ahead, so its slot
186 * start is later than the deadline. Keep the exact value: the recompute
187 * below only knows slot starts, and next_expiry must not exceed a deadline. */
188 rb_hrtime_t reinserted = TIMER_WHEEL_NO_EXPIRY;
189
190 for (int lvl = 0; lvl < TIMER_WHEEL_LEVELS; lvl++) {
191 int shift = lvl * TIMER_WHEEL_SLOT_BITS;
192 uint64_t from = prev_tick >> shift;
193 uint64_t to = now_tick >> shift;
194
195 if (to == from) break; // no boundary crossed; coarser levels crossed none either
196
197 uint64_t steps = to - from;
198 if (steps > TIMER_WHEEL_SLOTS) steps = TIMER_WHEEL_SLOTS;
199 struct timer_wheel_level *lv = &timer_th.wheel[lvl];
200
201 for (uint64_t tick = to - steps + 1; tick <= to; tick++) {
202 int slot = (int)(tick & (TIMER_WHEEL_SLOTS - 1));
203
204 if (!(lv->occupied & (UINT64_C(1) << slot))) continue;
205 lv->occupied &= ~(UINT64_C(1) << slot);
206
207 /* Detach first: a far-future waiter re-clamped by the insert below
208 * can land back on this very slot and must not be drained again. */
209 struct ccan_list_head pending;
210 ccan_list_head_init(&pending);
211 ccan_list_append_list(&pending, &lv->slots[slot]);
212
213 struct rb_thread_sched_waiting *w;
214 while ((w = ccan_list_pop(&pending, struct rb_thread_sched_waiting, node)) != NULL) {
215 if (timer_thread_check_exceed(w->data.timeout, now)) {
216 RUBY_DEBUG_LOG("expired th:%u", rb_th_serial(thread_sched_waiting_thread(w)));
217
218 /* flags stay set until the wakeup takes them under the
219 * owning lock (the fd shard for io waits, this one
220 * otherwise): a waiter whose flags are already cleared may
221 * run and re-register through this same `w`, which would
222 * relink the node we are still holding on `expired`. */
223 ccan_list_add_tail(expired, &w->node);
224 }
225 else {
226 /* arrived early: the distance shrank, so this lands on a
227 * finer level (or a farther slot of the coarsest one) */
228 if (w->data.timeout < reinserted) reinserted = w->data.timeout;
229 timer_wheel_insert(w);
230 }
231 }
232 }
233 }
234
235 timer_th.next_expiry = timer_wheel_next_expiry();
236 if (reinserted < timer_th.next_expiry) timer_th.next_expiry = reinserted;
237}
238
239/* Merge the wheel's next expiry into the poll timeout (ms; -1 = none).
240 * Checked even when the scheduler has other work (grq_cnt > 0). */
241static int
242timer_wheel_timeout(int timeout)
243{
244 rb_native_mutex_lock(&timer_th.waiting_lock);
245 {
246 if (timer_th.next_expiry != TIMER_WHEEL_NO_EXPIRY) {
247 rb_hrtime_t now = rb_hrtime_now();
248 rb_hrtime_t hrrel = rb_hrtime_sub(timer_th.next_expiry, now);
249
250 RUBY_DEBUG_LOG("now:%lu rel:%lu", (unsigned long)now, (unsigned long)hrrel);
251
252 rb_hrtime_t msec = (hrrel + RB_HRTIME_PER_MSEC - 1) / RB_HRTIME_PER_MSEC;
253 // A deadline further away than INT_MAX ms must clamp, not truncate:
254 // a negative timeout would be an untimed epoll_wait.
255 int thread_timeout = msec > INT_MAX ? INT_MAX : (int)msec; // ms
256
257 // Use minimum of scheduler timeout and thread sleep timeout
258 if (timeout < 0 || thread_timeout < timeout) {
259 timeout = thread_timeout;
260 }
261 }
262 }
263 rb_native_mutex_unlock(&timer_th.waiting_lock);
264
265 return timeout;
266}
267
268static void
269timer_thread_wakeup_thread_locked(struct rb_thread_sched *sched, rb_thread_t *th, uint32_t event_serial)
270{
271 if (sched->running != th && th->sched.event_serial == event_serial) {
272 thread_sched_to_ready_common(sched, th, true, false);
273 }
274}
275
276static void
277timer_thread_wakeup_thread(rb_thread_t *th, uint32_t event_serial)
278{
279 RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
280 struct rb_thread_sched *sched = TH_SCHED(th);
281
282 thread_sched_lock(sched, th);
283 {
284 timer_thread_wakeup_thread_locked(sched, th, event_serial);
285 }
286 thread_sched_unlock(sched, th);
287}
288
289#define TIMEOUT_WAKE_BATCH 16
290
291// One thread the timer thread is about to wake, with the serial it was armed at.
292struct timer_wake { rb_thread_t *th; uint32_t serial; };
293
294// Count a pending wake against a thread, so a dying thread can wait them out
295// (timer_thread_wake_fence). A count, not a flag: an expiry hold and an fd
296// event's wake can be pending on one thread at once. Take it while the lock
297// that pinned the thread (shard or waiting_lock) is still held.
298static void
299timer_wake_pending_inc(rb_thread_t *th)
300{
301 rb_native_mutex_lock(&timer_th.wake_pending_lock);
302 th->sched.wake_pending_cnt++;
303 rb_native_mutex_unlock(&timer_th.wake_pending_lock);
304}
305
306static void
307timer_wake_pending_dec(rb_thread_t *th)
308{
309 rb_native_mutex_lock(&timer_th.wake_pending_lock);
310 VM_ASSERT(th->sched.wake_pending_cnt > 0);
311 th->sched.wake_pending_cnt--;
312 rb_native_cond_broadcast(&timer_th.wake_pending_cond);
313 rb_native_mutex_unlock(&timer_th.wake_pending_lock);
314}
315
316static void
317timer_wake_pending_clear(struct timer_wake *batch, int n)
318{
319 for (int i = 0; i < n; i++) {
320 timer_wake_pending_dec(batch[i].th);
321 }
322}
323
324// Wait out pending wakes before a thread is freed: they would touch freed
325// memory, or wake a reused thread whose first serial matches a stale entry.
326static void
327timer_thread_wake_fence(rb_thread_t *th)
328{
329 if (!TIMER_THREAD_CREATED_P()) return;
330
331 rb_native_mutex_lock(&timer_th.wake_pending_lock);
332 while (th->sched.wake_pending_cnt > 0) {
333 rb_native_cond_wait(&timer_th.wake_pending_cond, &timer_th.wake_pending_lock);
334 }
335 rb_native_mutex_unlock(&timer_th.wake_pending_lock);
336}
337
338static void
339timer_thread_check_timeout(rb_vm_t *vm)
340{
341 rb_hrtime_t now = rb_hrtime_now();
342 uint64_t now_tick = timer_wheel_tick(now);
343 struct ccan_list_head expired;
344
345 ccan_list_head_init(&expired);
346
347 struct timer_wake batch[TIMEOUT_WAKE_BATCH];
348 bool more = true;
349
350 while (more) {
351 int n = 0;
352 struct { rb_thread_t *th; uint32_t serial; int fd; } io_claims[TIMEOUT_WAKE_BATCH];
353 int n_io = 0;
354
355 rb_native_mutex_lock(&timer_th.waiting_lock);
356 {
357 // A second pass finds the cursor already at now_tick and drains nothing.
358 if (now_tick > timer_th.wheel_cursor_tick) {
359 timer_wheel_drain(now, now_tick, &expired);
360 }
361
362 struct rb_thread_sched_waiting *w;
363 while (n + n_io < TIMEOUT_WAKE_BATCH &&
364 (w = ccan_list_pop(&expired, struct rb_thread_sched_waiting, node)) != NULL) {
365 // Name the thread and its serial here, then release it: once the
366 // flags are clear the thread may run and re-register through `w`,
367 // and a serial read after that would match the new registration.
368 // the pop leaves the node dangling; a concurrent claimer's
369 // wheel del (under this lock) must find it self-linked
370 ccan_list_node_init(&w->node);
371
372 if (w->flags & FD_WAIT_IO_MASK) {
373 // The fd shard owns these flags; claim below, once this
374 // lock is dropped. The pending count pins the thread: it
375 // was parked when we popped its node (a claimed entry
376 // leaves the wheel before its thread can wake).
377 io_claims[n_io].th = thread_sched_waiting_thread(w);
378 io_claims[n_io].serial = w->data.event_serial;
379 io_claims[n_io].fd = w->data.fd;
380 timer_wake_pending_inc(io_claims[n_io].th);
381 n_io++;
382 }
383 else {
384 // pin before the flags clear; see timer_thread_wake_fd_waiters
385 batch[n].th = thread_sched_waiting_thread(w);
386 batch[n].serial = w->data.event_serial;
387 timer_wake_pending_inc(batch[n].th);
388 w->flags = thread_sched_waiting_none;
389 w->data.result = 0;
390 n++;
391 }
392 }
393 more = !ccan_list_empty(&expired);
394 }
395 rb_native_mutex_unlock(&timer_th.waiting_lock);
396
397 for (int i = 0; i < n; i++) {
398 timer_thread_wakeup_thread(batch[i].th, batch[i].serial);
399 }
400 timer_wake_pending_clear(batch, n);
401
402 // The io entries race the fd event and the ubf for their flags.
403 for (int i = 0; i < n_io; i++) {
404 rb_thread_t *th = io_claims[i].th;
405 int fd = io_claims[i].fd;
406 bool claimed = false;
407
408 fd_shard_lock(fd);
409 {
410 struct rb_thread_sched_waiting *w = &th->sched.waiting_reason;
411
412 if (w->flags != thread_sched_waiting_none &&
413 w->data.event_serial == io_claims[i].serial) {
414 VM_ASSERT(w->data.fd == fd);
415 timer_thread_unregister_waiting(th, fd, w->flags);
416 w->flags = thread_sched_waiting_none;
417 w->data.result = 0;
418 claimed = true;
419 }
420 }
421 fd_shard_unlock(fd);
422
423 if (claimed) {
424 timer_thread_wakeup_thread(th, io_claims[i].serial);
425 }
426 timer_wake_pending_dec(th);
427 }
428 }
429}
430
431static bool
432timer_thread_cancel_waiting(rb_thread_t *th)
433{
434 struct rb_thread_sched_waiting *w = &th->sched.waiting_reason;
435
436 while (1) {
437 // Racy routing read; the claim is re-verified under the owning lock.
438 enum thread_sched_waiting_flag flags = w->flags;
439
440 if (flags == thread_sched_waiting_none) {
441 return false;
442 }
443 else if (flags & FD_WAIT_IO_MASK) {
444 int fd = w->data.fd;
445
446 fd_shard_lock(fd);
447 if ((w->flags & FD_WAIT_IO_MASK) && w->data.fd == fd) {
448 if (w->flags & thread_sched_waiting_timeout) {
449 rb_native_mutex_lock(&timer_th.waiting_lock);
450 timer_wheel_del(w);
451 rb_native_mutex_unlock(&timer_th.waiting_lock);
452 }
453 timer_thread_unregister_waiting(th, fd, w->flags);
454 w->flags = thread_sched_waiting_none;
455 fd_shard_unlock(fd);
456 return true;
457 }
458 fd_shard_unlock(fd);
459 }
460 else {
461 rb_native_mutex_lock(&timer_th.waiting_lock);
462 if (w->flags && !(w->flags & FD_WAIT_IO_MASK)) {
463 timer_wheel_del(w);
464 w->flags = thread_sched_waiting_none;
465 rb_native_mutex_unlock(&timer_th.waiting_lock);
466 return true;
467 }
468 rb_native_mutex_unlock(&timer_th.waiting_lock);
469 }
470 // lost the routing race; look again
471 }
472}
473
474static void
475ubf_event_waiting(void *ptr)
476{
477 rb_thread_t *th = (rb_thread_t *)ptr;
478 struct rb_thread_sched *sched = TH_SCHED(th);
479
480 RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
481
482 VM_ASSERT(th->nt == NULL || !th_has_dedicated_nt(th));
483
484 // only once. it is safe because th->interrupt_lock is already acquired.
485 th->unblock.func = NULL;
486 th->unblock.arg = NULL;
487
488 thread_sched_lock(sched, th);
489 {
490 bool canceled = timer_thread_cancel_waiting(th);
491
492 if (sched->running == th) {
493 RUBY_DEBUG_LOG("not waiting yet");
494 }
495 else if (canceled) {
496 thread_sched_to_ready_common(sched, th, true, false);
497 }
498 else {
499 RUBY_DEBUG_LOG("already not waiting");
500 }
501 }
502 thread_sched_unlock(sched, th);
503}
504
505// Why timer_thread_register_waiting() did or did not take over the wait. Both
506// "not registered" cases used to share one value; only the first means ready.
507enum timer_thread_register_result {
508 timer_thread_registered, // the timer thread owns this wait now
509 timer_thread_already_ready, // no wait needed: the fd is ready, or no timeout
510 timer_thread_unavailable, // cannot be registered; the caller must fall back
511};
512
513static enum timer_thread_register_result
514timer_thread_register_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags, rb_hrtime_t *rel, uint32_t event_serial);
515
516// Arm a timeout-only wake on the timer thread for a Ractor wait. Returns false
517// if the deadline has already passed, in which case nothing was registered.
518static bool
519ractor_sched_timeout_arm(rb_thread_t *th, const rb_hrtime_t *rel)
520{
521 rb_hrtime_t rel_copy = *rel;
522
523 return timer_thread_register_waiting(th, -1, thread_sched_waiting_timeout, &rel_copy,
524 ++th->sched.event_serial) == timer_thread_registered;
525}
526
527// Returns true if the timeout was still armed, i.e. it did not fire.
528static bool
529ractor_sched_timeout_disarm(rb_thread_t *th)
530{
531 return timer_thread_cancel_waiting(th);
532}
533
534// return how the wait ended; see enum thread_sched_wait_result
535static enum thread_sched_wait_result
536thread_sched_wait_events(struct rb_thread_sched *sched, rb_thread_t *th, int fd, enum thread_sched_waiting_flag events, rb_hrtime_t *rel)
537{
538 VM_ASSERT(!th_has_dedicated_nt(th)); // on SNT
539
540 volatile bool timedout = false, need_cancel = false;
541 volatile enum timer_thread_register_result reg = timer_thread_unavailable;
542
543 uint32_t event_serial = ++th->sched.event_serial; // overflow is okay
544
545
546 thread_sched_lock(sched, th);
547 {
548 // NOTE: there's a lock ordering inversion here with the ubf call, but it's benign.
549 if (ubf_set(th, ubf_event_waiting, (void *)th, NULL)) {
550 // Already interrupted: the fd was never looked at, so this is no event.
551 thread_sched_unlock(sched, th);
552 return thread_sched_wait_interrupted;
553 }
554
555 reg = timer_thread_register_waiting(th, fd, events, rel, event_serial);
556
557 if (reg == timer_thread_registered) {
558 RUBY_DEBUG_LOG("wait fd:%d", fd);
559
560 RB_VM_SAVE_MACHINE_CONTEXT(th);
561
562 RB_INTERNAL_THREAD_HOOK(RUBY_INTERNAL_THREAD_EVENT_SUSPENDED, th);
563
564 if (th->sched.waiting_reason.flags == thread_sched_waiting_none) {
565 th->sched.event_serial++;
566 // timer thread has dequeued us already, but it won't try to wake us because we bumped our serial
567 }
568 else if (RUBY_VM_INTERRUPTED(th->ec)) {
569 th->sched.event_serial++; // make sure timer thread doesn't try to wake us
570 need_cancel = true;
571 }
572 else {
573 RUBY_DEBUG_LOG("sleep");
574
575 // A sleeper's status belongs to the caller: sleep_hrtime
576 // re-sleeps while it stays THREAD_STOPPED and only a waker may
577 // change it, as with native_cond_sleep on a dedicated nt. An
578 // io wait enters as THREAD_RUNNABLE and shows "sleep" while
579 // parked, as a dedicated nt's blocking region does.
580 enum rb_thread_status prev_status = th->status;
581 if (prev_status == THREAD_RUNNABLE) th->status = THREAD_STOPPED_FOREVER;
582 thread_sched_wakeup_next_thread(sched, th, true);
583 thread_sched_wait_running_turn(sched, th, true, NULL);
584 if (prev_status == THREAD_RUNNABLE) th->status = THREAD_RUNNABLE;
585
586 RUBY_DEBUG_LOG("wakeup");
587 }
588
589 timedout = th->sched.waiting_reason.data.result == 0;
590
591 if (need_cancel) {
592 timer_thread_cancel_waiting(th);
593 }
594 }
595 else {
596 // Ready right now, or not registerable at all -- only the former may
597 // be reported as readiness.
598 RUBY_DEBUG_LOG("did not wait fd:%d reg:%d", fd, (int)reg);
599 }
600 }
601 thread_sched_unlock(sched, th);
602
603 // if ubf triggered between sched unlock and ubf clear, sched->running == th here
604 ubf_clear(th, false);
605
606 VM_ASSERT(sched->running == th);
607
608 if (reg == timer_thread_unavailable) return thread_sched_wait_unavailable;
609 // A ready fd never registered, so it never timed out either.
610 if (reg == timer_thread_already_ready) return thread_sched_wait_event;
611 // No event fired and we are interrupted: that is an interrupt, not a timeout.
612 if (timedout && RUBY_VM_INTERRUPTED(th->ec)) return thread_sched_wait_interrupted;
613 return timedout ? thread_sched_wait_timeout : thread_sched_wait_event;
614}
615
617
618static int
619get_sysconf_page_size(void)
620{
621 static long page_size = 0;
622
623 if (UNLIKELY(page_size == 0)) {
624 page_size = sysconf(_SC_PAGESIZE);
625 VM_ASSERT(page_size < INT_MAX);
626 }
627 return (int)page_size;
628}
629
630#define MSTACK_CHUNK_SIZE (512 * 1024 * 1024) // 512MB
631#define MSTACK_PAGE_SIZE get_sysconf_page_size()
632#define MSTACK_CHUNK_PAGE_NUM (MSTACK_CHUNK_SIZE / MSTACK_PAGE_SIZE - 1) // 1 is start redzone
633
634// 512MB chunk
635// 131,072 pages (> 65,536)
636// Head pages hold the chunk header (see start_page); stacks follow.
637
638/*
639 * <--> machine stack + vm stack
640 * ----------------------------------
641 * |HD...|RZ| ... |RZ| ... ... |RZ|
642 * <------------- 512MB ------------->
643 */
644
645static struct nt_stack_chunk_header {
646 struct nt_stack_chunk_header *prev_chunk;
647 struct nt_stack_chunk_header *prev_free_chunk;
648 // prev_free_chunk == NULL cannot double as the membership test: the free
649 // list's tail also has it NULL, and re-pushing the tail self-cycles it.
650 bool on_free_list;
651
652 uint16_t start_page;
653 uint16_t stack_count;
654 uint16_t uninitialized_stack_count;
655
656 uint16_t free_stack_pos;
657 uint16_t free_stack[];
658} *nt_stack_chunks = NULL,
659 *nt_free_stack_chunks = NULL;
660
661struct nt_machine_stack_footer {
662 struct nt_stack_chunk_header *ch;
663 size_t index;
664#ifdef HAVE_VALGRIND_MEMCHECK_H
665 unsigned int valgrind_stack_id;
666#endif
667};
668
669static rb_nativethread_lock_t nt_machine_stack_lock = RB_NATIVETHREAD_LOCK_INIT;
670
671// The holder at the fork moment does not exist in the child; start over.
672static void
673nt_machine_stack_atfork(void)
674{
675 rb_native_mutex_initialize(&nt_machine_stack_lock);
676}
677
678#include <sys/mman.h>
679
680// Page-align the configured sizes: the layout puts a guard page and a
681// MAP_FIXED machine stack behind the VM stack, and both must land on page
682// boundaries whatever RUBY_THREAD_VM_STACK_SIZE and
683// RUBY_THREAD_MACHINE_STACK_SIZE hold (those align only to 4KB).
684static inline size_t
685nt_vm_stack_area(const rb_vm_t *vm)
686{
687 return (size_t)roomof(vm->default_params.thread_vm_stack_size, MSTACK_PAGE_SIZE) * MSTACK_PAGE_SIZE;
688}
689
690static inline size_t
691nt_machine_stack_area(const rb_vm_t *vm)
692{
693 return (size_t)roomof(vm->default_params.thread_machine_stack_size, MSTACK_PAGE_SIZE) * MSTACK_PAGE_SIZE;
694}
695
696// vm stack area + guard page + machine stack area
697static inline size_t
698nt_thread_stack_size(void)
699{
700 static size_t msz;
701 if (LIKELY(msz > 0)) return msz;
702
703 rb_vm_t *vm = GET_VM();
704 msz = nt_vm_stack_area(vm) + MSTACK_PAGE_SIZE + nt_machine_stack_area(vm);
705 return msz;
706}
707
708static struct nt_stack_chunk_header *
709nt_alloc_thread_stack_chunk(void)
710{
711 const char *m = (void *)mmap(NULL, MSTACK_CHUNK_SIZE, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
712 if (m == MAP_FAILED) {
713 return NULL;
714 }
715
716 ruby_annotate_mmap(m, MSTACK_CHUNK_SIZE, "Ruby:nt_alloc_thread_stack_chunk");
717
718 size_t msz = nt_thread_stack_size();
719 int header_page_cnt = 1;
720 int stack_count = ((MSTACK_CHUNK_PAGE_NUM - header_page_cnt) * MSTACK_PAGE_SIZE) / msz;
721 int ch_size = sizeof(struct nt_stack_chunk_header) + sizeof(uint16_t) * stack_count;
722
723 if (ch_size > MSTACK_PAGE_SIZE * header_page_cnt) {
724 header_page_cnt = (ch_size + MSTACK_PAGE_SIZE - 1) / MSTACK_PAGE_SIZE;
725 stack_count = ((MSTACK_CHUNK_PAGE_NUM - header_page_cnt) * MSTACK_PAGE_SIZE) / msz;
726 }
727
728 VM_ASSERT(stack_count <= UINT16_MAX);
729
730 // Enable read/write for the header pages
731 if (mprotect((void *)m, (size_t)header_page_cnt * MSTACK_PAGE_SIZE, PROT_READ | PROT_WRITE) != 0) {
732 munmap((void *)m, MSTACK_CHUNK_SIZE);
733 return NULL;
734 }
735
736 struct nt_stack_chunk_header *ch = (struct nt_stack_chunk_header *)m;
737
738 ch->start_page = header_page_cnt;
739 ch->prev_chunk = nt_stack_chunks;
740 ch->prev_free_chunk = nt_free_stack_chunks;
741 ch->on_free_list = true; // the caller makes it the free-list head
742 ch->uninitialized_stack_count = ch->stack_count = (uint16_t)stack_count;
743 ch->free_stack_pos = 0;
744
745 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);
746
747 return ch;
748}
749
750static void *
751nt_stack_chunk_get_stack_start(struct nt_stack_chunk_header *ch, size_t idx)
752{
753 const char *m = (char *)ch;
754 return (void *)(m + ch->start_page * MSTACK_PAGE_SIZE + idx * nt_thread_stack_size());
755}
756
757static struct nt_machine_stack_footer *
758nt_stack_chunk_get_msf(const rb_vm_t *vm, const char *mstack)
759{
760 // TODO: stack direction
761 const size_t msz = vm->default_params.thread_machine_stack_size;
762 return (struct nt_machine_stack_footer *)&mstack[msz - sizeof(struct nt_machine_stack_footer)];
763}
764
765static void
766nt_stack_chunk_get_stack(const rb_vm_t *vm, struct nt_stack_chunk_header *ch, size_t idx, void **vm_stack, void **machine_stack)
767{
768 // TODO: only support stack going down
769 // [VM ... <GUARD> machine stack ...]
770
771 const char *vstack, *mstack;
772 const char *guard_page;
773 vstack = nt_stack_chunk_get_stack_start(ch, idx);
774 guard_page = vstack + nt_vm_stack_area(vm);
775 mstack = guard_page + MSTACK_PAGE_SIZE;
776
777 struct nt_machine_stack_footer *msf = nt_stack_chunk_get_msf(vm, mstack);
778 msf->ch = ch;
779 msf->index = idx;
780#ifdef HAVE_VALGRIND_MEMCHECK_H
781 msf->valgrind_stack_id = VALGRIND_STACK_REGISTER(mstack, (const char *)msf - 1);
782#endif
783
784#if 0
785 RUBY_DEBUG_LOG("msf:%p vstack:%p-%p guard_page:%p-%p mstack:%p-%p", msf,
786 vstack, (void *)(guard_page-1),
787 guard_page, (void *)(mstack-1),
788 mstack, (void *)(msf));
789#endif
790
791 *vm_stack = (void *)vstack;
792 *machine_stack = (void *)mstack;
793}
794
796static void
797nt_stack_chunk_dump(void)
798{
799 struct nt_stack_chunk_header *ch;
800 int i;
801
802 fprintf(stderr, "** nt_stack_chunks\n");
803 ch = nt_stack_chunks;
804 for (i=0; ch; i++, ch = ch->prev_chunk) {
805 fprintf(stderr, "%d %p free_pos:%d\n", i, (void *)ch, (int)ch->free_stack_pos);
806 }
807
808 fprintf(stderr, "** nt_free_stack_chunks\n");
809 ch = nt_free_stack_chunks;
810 for (i=0; ch; i++, ch = ch->prev_free_chunk) {
811 fprintf(stderr, "%d %p free_pos:%d\n", i, (void *)ch, (int)ch->free_stack_pos);
812 }
813}
814
815static int
816nt_alloc_stack(rb_vm_t *vm, void **vm_stack, void **machine_stack)
817{
818 int err = 0;
819
820 rb_native_mutex_lock(&nt_machine_stack_lock);
821 {
822 retry:
823 if (nt_free_stack_chunks) {
824 struct nt_stack_chunk_header *ch = nt_free_stack_chunks;
825 if (ch->free_stack_pos > 0) {
826 RUBY_DEBUG_LOG("free_stack_pos:%d", ch->free_stack_pos);
827 nt_stack_chunk_get_stack(vm, ch, ch->free_stack[--ch->free_stack_pos], vm_stack, machine_stack);
828 }
829 else if (ch->uninitialized_stack_count > 0) {
830 RUBY_DEBUG_LOG("uninitialized_stack_count:%d", ch->uninitialized_stack_count);
831
832 size_t idx = ch->stack_count - ch->uninitialized_stack_count--;
833
834 // The chunk was mapped PROT_NONE; enable the VM stack and
835 // machine stack pages, leaving the guard page as PROT_NONE.
836 char *stack_start = nt_stack_chunk_get_stack_start(ch, idx);
837 size_t vm_stack_area = nt_vm_stack_area(vm);
838 size_t mstack_size = nt_thread_stack_size() - vm_stack_area - MSTACK_PAGE_SIZE;
839 char *mstack_start = stack_start + vm_stack_area + MSTACK_PAGE_SIZE;
840
841 int mstack_flags = MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE;
842#if defined(MAP_STACK) && !defined(__FreeBSD__)
843 mstack_flags |= MAP_STACK;
844#endif
845
846 if (mprotect(stack_start, vm_stack_area, PROT_READ | PROT_WRITE) != 0 ||
847 mmap(mstack_start, mstack_size, PROT_READ | PROT_WRITE, mstack_flags, -1, 0) == MAP_FAILED) {
848 err = errno;
849 ch->uninitialized_stack_count++; // the slot was not consumed
850 }
851 else {
852 nt_stack_chunk_get_stack(vm, ch, idx, vm_stack, machine_stack);
853 }
854 }
855 else {
856 nt_free_stack_chunks = ch->prev_free_chunk;
857 ch->prev_free_chunk = NULL;
858 ch->on_free_list = false;
859 goto retry;
860 }
861 }
862 else {
863 struct nt_stack_chunk_header *p = nt_alloc_thread_stack_chunk();
864 if (p == NULL) {
865 err = errno;
866 }
867 else {
868 nt_free_stack_chunks = nt_stack_chunks = p;
869 goto retry;
870 }
871 }
872 }
873 rb_native_mutex_unlock(&nt_machine_stack_lock);
874
875 return err;
876}
877
878static void
879nt_madvise_free_or_dontneed(void *addr, size_t len)
880{
881 /* There is no real way to perform error handling here. Both MADV_FREE
882 * and MADV_DONTNEED are both documented to pretty much only return EINVAL
883 * for a huge variety of errors. It's indistinguishable if madvise fails
884 * because the parameters were bad, or because the kernel we're running on
885 * does not support the given advice. This kind of free-but-don't-unmap
886 * is best-effort anyway, so don't sweat it.
887 *
888 * n.b. A very common case of "the kernel doesn't support MADV_FREE and
889 * returns EINVAL" is running under the `rr` debugger; it makes all
890 * MADV_FREE calls return EINVAL. */
891
892#if defined(MADV_FREE)
893 int r = madvise(addr, len, MADV_FREE);
894 // Return on success, or else try MADV_DONTNEED
895 if (r == 0) return;
896#endif
897#if defined(MADV_DONTNEED)
898 madvise(addr, len, MADV_DONTNEED);
899#endif
900}
901
902static void
903nt_free_stack(void *mstack)
904{
905 if (!mstack) return;
906
907 rb_native_mutex_lock(&nt_machine_stack_lock);
908 {
909 struct nt_machine_stack_footer *msf = nt_stack_chunk_get_msf(GET_VM(), mstack);
910 struct nt_stack_chunk_header *ch = msf->ch;
911 int idx = (int)msf->index;
912 void *stack = nt_stack_chunk_get_stack_start(ch, idx);
913
914 RUBY_DEBUG_LOG("stack:%p mstack:%p ch:%p index:%d", stack, mstack, ch, idx);
915#ifdef HAVE_VALGRIND_MEMCHECK_H
916 VALGRIND_STACK_DEREGISTER(msf->valgrind_stack_id);
917#endif
918
919 if (!ch->on_free_list) {
920 ch->on_free_list = true;
921 ch->prev_free_chunk = nt_free_stack_chunks;
922 nt_free_stack_chunks = ch;
923 }
924 ch->free_stack[ch->free_stack_pos++] = idx;
925
926 // clear the stack pages
927 nt_madvise_free_or_dontneed(stack, nt_thread_stack_size());
928 }
929 rb_native_mutex_unlock(&nt_machine_stack_lock);
930}
931
932static bool
933mn_threads_enabled_p(void)
934{
935 return mn_threads_mode >= 0;
936}
937
938static int
939native_thread_check_and_create_shared(rb_vm_t *vm)
940{
941 bool need_to_make = false;
942
943 if (!mn_threads_enabled_p()) return 0; // no thread is M:N: the pool serves nobody
944
945 ractor_sched_lock(vm, NULL); // NULL: the timer thread also calls this
946 {
947 unsigned int schedulable_ractor_cnt = vm->ractor.cnt;
948 RUBY_ASSERT(schedulable_ractor_cnt >= 1);
949
950 if (!vm->ractor.main_ractor->threads.sched.enable_mn_threads)
951 schedulable_ractor_cnt--; // do not need snt for main ractor
952
953 // CAS keeps a concurrent rejoin from pushing snt_cnt past the cap
954 rb_atomic_t snt_cnt = RUBY_ATOMIC_LOAD(vm->ractor.sched.snt_cnt);
955 while (((int)snt_cnt < MINIMUM_SNT) ||
956 (snt_cnt < schedulable_ractor_cnt &&
957 snt_cnt < vm->ractor.sched.max_cpu)) {
958 rb_atomic_t prev = RUBY_ATOMIC_CAS(vm->ractor.sched.snt_cnt, snt_cnt, snt_cnt + 1);
959 if (prev == snt_cnt) {
960 need_to_make = true;
961 break;
962 }
963 snt_cnt = prev;
964 }
965
966 if (need_to_make) {
967 RUBY_DEBUG_LOG("added snt:%u dnt:%u ractor_cnt:%u grq_cnt:%u",
968 vm->ractor.sched.snt_cnt,
969 vm->ractor.sched.dnt_cnt,
970 vm->ractor.cnt,
971 vm->ractor.sched.grq_cnt);
972 }
973 else {
974 RUBY_DEBUG_LOG("snt:%d ractor_cnt:%d", (int)vm->ractor.sched.snt_cnt, (int)vm->ractor.cnt);
975 }
976 }
977 ractor_sched_unlock(vm, NULL);
978
979 if (need_to_make) {
980 struct rb_native_thread *nt = native_thread_alloc();
981 nt->vm = vm;
982 int err = native_thread_create0(nt);
983 if (err) {
984 // Roll back, or this function would conclude forever that the
985 // pool is wide enough and never try again.
986 ractor_sched_lock(vm, NULL);
987 RUBY_ATOMIC_DEC(vm->ractor.sched.snt_cnt);
988 ractor_sched_unlock(vm, NULL);
989 native_thread_destroy(nt);
990 }
991 return err;
992 }
993 else {
994 return 0;
995 }
996}
997
998// A coroutine thread's epilogue, run from thread_start_func_2 while th is
999// still valid. Everything that touches th happens here; co_start then only
1000// makes the final transfer, touching the execution-owned tctx alone.
1001static void
1002coroutine_thread_terminated(rb_thread_t *th)
1003{
1004 struct rb_thread_context *tctx = (struct rb_thread_context *)th->sched.context;
1005 struct rb_thread_sched *sched = TH_SCHED(th);
1006 rb_ractor_t *r = th->ractor;
1007 bool last = (th->invoke_type == thread_invoke_type_ractor_proc);
1008 bool is_dnt = th_has_dedicated_nt(th);
1009
1010 // VM destruct tears down the heap and then unsets ruby_current_vm_ptr;
1011 // this native thread still frees the dead context afterwards (the nt
1012 // loop's reclaim uses ruby_xfree and the stack-pool geometry via
1013 // GET_VM()). Make destruct wait until the reclaim finished. (Observed:
1014 // an assert_separately child exiting right after a Ractor finished
1015 // crashed at GET_VM()->default_params, offset 0x2600, on two arches.)
1016 rb_vm_t *const vm = th->vm; // survives th; the tail below must not read th
1017 RUBY_ATOMIC_INC(vm->ractor.sched.winding_cnt);
1018
1019 rb_thread_t *wake_th;
1020 bool wake_mn = false;
1021
1022 // Leave the living set here, while th is still barrier-registered and no
1023 // successor can run: the GC's root scan walks r->threads.set without the
1024 // Ractor lock, so the unlink must not race with it. Off the set th would
1025 // be unreachable although the handoff below keeps using it (and the GC can
1026 // run: to_dead_common() deregisters th, so no barrier waits for it) --
1027 // dying_th keeps it marked until its last use.
1028 VM_ASSERT(sched->running == th); // th owns the slot through the handoff
1029 if (!last) {
1030 RUBY_ATOMIC_PTR_SET(r->threads.dying_th, th);
1031 rb_ractor_living_threads_remove(r, th);
1032 }
1033
1034 thread_sched_lock(sched, th);
1035 {
1036 // designate the successor (running = next from readyq, or NULL); for
1037 // a dedicated nt (will_switch false) this also enqueues the Ractor.
1038 thread_sched_to_dead_common(sched, th);
1039
1040 // Only the successor WE designated here may be enqueued by this
1041 // epilogue (below). If readyq was empty, running is now NULL and a
1042 // waker (e.g. the timer thread) that later installs a runnable
1043 // thread enqueues the Ractor itself -- enqueuing "whatever is
1044 // running" at that point would duplicate its entry.
1045 wake_th = is_dnt ? NULL : sched->running;
1046 // Read wake_th->nt under the lock: a dedicated successor was already
1047 // woken by to_dead_common and may die (freeing wake_th) as soon as we
1048 // unlock. An M:N successor (nt == NULL) cannot run or be assigned an
1049 // nt before our enqueue below, so the value cannot go stale.
1050 wake_mn = (wake_th != NULL && wake_th->nt == NULL);
1051
1052 tctx->nt = th->nt; // stash the final transfer target for co_start
1053 native_thread_assign(NULL, th);
1054 th->sched.context = NULL; // the wrapper's dfree must not reclaim tctx
1055
1056 if (!last) {
1057 // Still under the sched lock: a successor (even a dedicated one
1058 // woken by to_dead_common) starts by taking it, so it cannot
1059 // observe or overwrite these until we unlock. th was last used
1060 // above and running_ec no longer points into it; now it may be
1061 // collected.
1062 rb_ractor_set_current_ec(r, NULL); // r alive: it has other threads
1063 VM_ASSERT(RUBY_ATOMIC_PTR_LOAD(r->threads.dying_th) == th);
1064 RUBY_ATOMIC_PTR_SET(r->threads.dying_th, NULL);
1065 }
1066 }
1067 if (last) {
1068 thread_sched_unlock(sched, th); // th is still on the living set here
1069
1070 VM_ASSERT(sched->running == NULL);
1071 VM_ASSERT(wake_th == NULL);
1072 // Last access to th/r: the removal may unlink the Ractor, after
1073 // which the GC may collect th and r.
1074 rb_ractor_living_threads_remove(r, th);
1075 rb_current_ec_set(NULL); // TLS only; r may be collectable already
1076 }
1077 else {
1078 // th lost its root at the clear above; the plain unlock's debug log
1079 // would read th->serial.
1080 thread_sched_unlock_no_log(sched, th);
1081
1082 if (wake_mn) {
1083 // enqueue the successor designated above -- exactly once per
1084 // "runnable but unserved" period, by its designator.
1085 thread_sched_lock(sched, NULL);
1086 ractor_sched_enq(vm, r);
1087 thread_sched_unlock(sched, NULL);
1088 }
1089 }
1090}
1091
1092#ifdef __APPLE__
1093# define co_start ruby_coroutine_start
1094#else
1095static
1096#endif
1097COROUTINE
1098co_start(struct coroutine_context *from, struct coroutine_context *self)
1099{
1100#ifdef RUBY_ASAN_ENABLED
1101 __sanitizer_finish_switch_fiber(self->fake_stack,
1102 (const void**)&from->stack_base, &from->stack_size);
1103#endif
1104
1105 rb_thread_t *th = (rb_thread_t *)self->argument;
1106 struct rb_thread_sched *sched = TH_SCHED(th);
1107 VM_ASSERT(th->nt != NULL);
1108 VM_ASSERT(th == sched->running);
1109 VM_ASSERT(sched->lock_owner == NULL);
1110
1111 // RUBY_DEBUG_LOG("th:%u", rb_th_serial(th));
1112
1113 thread_sched_set_locked(sched, th);
1114 thread_sched_add_running_thread(TH_SCHED(th), th);
1115 thread_sched_unlock(sched, th);
1116 {
1117 RB_INTERNAL_THREAD_HOOK(RUBY_INTERNAL_THREAD_EVENT_RESUMED, th);
1118 call_thread_start_func_2(th);
1119 }
1120 // Thread is terminated. coroutine_thread_terminated (run from
1121 // thread_start_func_2 while th was still valid) already left the living
1122 // set and stashed the transfer target, so th / its Ractor may already be
1123 // collected. Only tctx is touched here: mark it dead and transfer back to
1124 // this native thread's own context, where the nt loop reclaims tctx.
1125 struct rb_thread_context *tctx = (struct rb_thread_context *)self;
1126 tctx->dead = true;
1127 // Hand this context to the nt's loop, which reclaims it right after the
1128 // final transfer returns from switch0.
1129 tctx->nt->dead_co = &tctx->co;
1130 coroutine_transfer0(&tctx->co, tctx->nt->nt_context, true);
1131
1132 rb_bug("unreachable");
1133}
1134
1135static int
1136native_thread_create_shared(rb_thread_t *th)
1137{
1138 // setup coroutine
1139 rb_vm_t *vm = th->vm;
1140 void *vm_stack = NULL, *machine_stack = NULL;
1141 int err = nt_alloc_stack(vm, &vm_stack, &machine_stack);
1142 if (err) return err;
1143
1144 VM_ASSERT(vm_stack < machine_stack);
1145
1146 // setup vm stack
1147 size_t vm_stack_words = th->vm->default_params.thread_vm_stack_size/sizeof(VALUE);
1148 rb_ec_initialize_vm_stack(th->ec, vm_stack, vm_stack_words);
1149
1150 // setup machine stack
1151 size_t machine_stack_size = vm->default_params.thread_machine_stack_size - sizeof(struct nt_machine_stack_footer);
1152 th->ec->machine.stack_start = (void *)((uintptr_t)machine_stack + machine_stack_size);
1153 th->ec->machine.stack_maxsize = machine_stack_size; // TODO
1154 th->sched.context_stack = machine_stack;
1155 th->sched.context_stack_size = machine_stack_size;
1156
1157 struct rb_thread_context *tctx = ruby_xmalloc(sizeof(struct rb_thread_context));
1158 tctx->stack = machine_stack;
1159 tctx->dead = false;
1160 tctx->nt = NULL;
1161 th->sched.context = &tctx->co;
1162 coroutine_initialize(&tctx->co, co_start, machine_stack, machine_stack_size);
1163 tctx->co.argument = th;
1164
1165 RUBY_DEBUG_LOG("th:%u vm_stack:%p machine_stack:%p", rb_th_serial(th), vm_stack, machine_stack);
1166
1167 // Widen the pool before publishing th. Once ready, a Ractor's thread that
1168 // runs to its end frees its own rb_thread_t (rb_ractor_postmortem_free),
1169 // and the caller's create-failure path assumes th never became runnable.
1170 int create_err = native_thread_check_and_create_shared(vm);
1171 if (create_err) return create_err;
1172
1173 thread_sched_to_ready(TH_SCHED(th), th);
1174 return 0;
1175}
1176
1178#if HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H
1179
1183
1184// (FD_WAIT_IO_MASK and the fd shard helpers are defined near the top.)
1185
1186#define FDMAP_CHUNK_BITS 10
1187#define FDMAP_CHUNK_SIZE (1u << FDMAP_CHUNK_BITS)
1188#define FDMAP_CHUNK_MASK (FDMAP_CHUNK_SIZE - 1)
1189
1190// Callable under any fd shard lock: a chunk spans every shard, so the chunk
1191// table is not guarded by them; slots install by CAS and are never freed.
1192static struct rb_fd_waiters *
1193fd_waiters_lookup(int fd, bool create)
1194{
1195 if (fd < 0) return NULL;
1196
1197 unsigned int ci = (unsigned int)fd >> FDMAP_CHUNK_BITS;
1198 if (ci >= FDMAP_MAX_CHUNKS) return NULL; // the caller falls back to a blocking wait
1199
1200 struct rb_fd_waiters *chunk = RUBY_ATOMIC_PTR_LOAD(timer_th.fdmap_chunks[ci]);
1201
1202 if (chunk == NULL) {
1203 if (!create) return NULL;
1204
1205 chunk = calloc(FDMAP_CHUNK_SIZE, sizeof(*chunk));
1206 if (chunk == NULL) rb_bug("fd_waiters_lookup: calloc failed");
1207
1208 for (unsigned int i = 0; i < FDMAP_CHUNK_SIZE; i++) {
1209 ccan_list_head_init(&chunk[i].waiters);
1210 }
1211
1212 struct rb_fd_waiters *prev = RUBY_ATOMIC_PTR_CAS(timer_th.fdmap_chunks[ci], NULL, chunk);
1213 if (prev != NULL) {
1214 free(chunk); // another shard installed it first
1215 chunk = prev;
1216 }
1217 }
1218
1219 return &chunk[(unsigned int)fd & FDMAP_CHUNK_MASK];
1220}
1221
1222// The fd's shard lock must be held.
1223static uint32_t
1224fd_waiters_union(struct rb_fd_waiters *e)
1225{
1226 uint32_t want = 0;
1227 struct rb_thread_sched_waiting *w;
1228
1229 ccan_list_for_each(&e->waiters, w, fd_node) {
1230 want |= (uint32_t)(w->flags & FD_WAIT_IO_MASK);
1231 }
1232 return want;
1233}
1234
1235// Events name an fd and the generation it was armed with, never a thread: a
1236// stale event then resolves to a table lookup instead of a freed thread.
1237static inline uint64_t
1238fd_event_tag(int fd, uint32_t generation)
1239{
1240 return ((uint64_t)generation << 32) | (uint32_t)fd;
1241}
1242
1243#define FD_EVENT_TAG_FD(tag) ((int)((tag) & 0xffffffffu))
1244#define FD_EVENT_TAG_GEN(tag) ((uint32_t)((tag) >> 32))
1245
1246// Make the backend match `want`. Returns false if the fd cannot be registered
1247// at all (closed, or unsupported by the backend), leaving the entry untouched.
1248// The fd's shard lock must be held. `consumed` says an epoll event for the
1249// current arming was just delivered, so EPOLLONESHOT has already disarmed it.
1250static bool
1251fd_waiters_arm(int fd, struct rb_fd_waiters *e, uint32_t want, bool consumed)
1252{
1253 // After a delivery the kernel side is disarmed even when the flags agree,
1254 // so a consumed call must fall through to re-arm.
1255 if (want == e->armed_flags && !consumed) return true;
1256
1257#if HAVE_SYS_EVENT_H
1258 struct kevent ke[2];
1259 int n = 0;
1260 uint32_t add = want & ~e->armed_flags;
1261 uint32_t del = e->armed_flags & ~want;
1262 void *tag = (void *)(uintptr_t)fd_event_tag(fd, e->generation);
1263
1264 if (del & thread_sched_waiting_io_read) { EV_SET(&ke[n], fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); n++; }
1265 if (del & thread_sched_waiting_io_write) { EV_SET(&ke[n], fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); n++; }
1266
1267 if (n > 0 && kevent(timer_th.event_fd, ke, n, NULL, 0, NULL) == -1) {
1268 // The fd may already be gone; that is not an error for a removal.
1269 if (errno != ENOENT && errno != EBADF) {
1270 perror("kevent");
1271 rb_bug("fd_waiters_arm/kevent delete failed (fd:%d errno:%d)", fd, errno);
1272 }
1273 }
1274
1275 n = 0;
1276 if (add & thread_sched_waiting_io_read) { EV_SET(&ke[n], fd, EVFILT_READ, EV_ADD, 0, 0, tag); n++; }
1277 if (add & thread_sched_waiting_io_write) { EV_SET(&ke[n], fd, EVFILT_WRITE, EV_ADD, 0, 0, tag); n++; }
1278
1279 if (n > 0 && kevent(timer_th.event_fd, ke, n, NULL, 0, NULL) == -1) {
1280 switch (errno) {
1281 case EBADF:
1282 case EINVAL:
1283 return false;
1284 default:
1285 perror("kevent");
1286 rb_bug("fd_waiters_arm/kevent add failed (fd:%d errno:%d)", fd, errno);
1287 }
1288 }
1289#elif HAVE_SYS_EPOLL_H
1290 if (want == 0) {
1291 // A delivered oneshot event has already disarmed the fd; otherwise DEL
1292 // it. MOD to no events would not do: EPOLLHUP and EPOLLERR are
1293 // reported whatever the mask asks for, and without EPOLLONESHOT they
1294 // are reported level-triggered, so a registration left behind by a
1295 // waiter that gave up (kill, interrupt, timeout) spins the timer
1296 // thread once the fd hangs up -- and a spinning timer thread never
1297 // reaches its timeout branch, the only place that mints an snt.
1298 if (!consumed && e->registered) {
1299 if (epoll_ctl(timer_th.event_fd, EPOLL_CTL_DEL, fd, NULL) == -1) {
1300 switch (errno) {
1301 case EBADF:
1302 case ENOENT:
1303 // the fd is already closed or gone from the set
1304 break;
1305 default:
1306 perror("epoll_ctl");
1307 rb_bug("fd_waiters_arm/epoll_ctl disarm failed (fd:%d errno:%d)", fd, errno);
1308 }
1309 }
1310 e->registered = false;
1311 }
1312 // Anything epoll_wait already queued for the old arming is stale now.
1313 e->generation++;
1314 e->armed_flags = 0;
1315 return true;
1316 }
1317
1318 uint32_t epoll_events = EPOLLONESHOT;
1319 if (want & thread_sched_waiting_io_read) epoll_events |= EPOLLIN;
1320 if (want & thread_sched_waiting_io_write) epoll_events |= EPOLLOUT;
1321
1322 struct epoll_event event = {
1323 .events = epoll_events,
1324 .data = { .u64 = fd_event_tag(fd, e->generation) },
1325 };
1326
1327 int op = e->registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD;
1328
1329 if (epoll_ctl(timer_th.event_fd, op, fd, &event) == -1) {
1330 switch (errno) {
1331 case ENOENT:
1332 // Not registered after all: the fd was closed and reopened. Add it.
1333 if (op == EPOLL_CTL_MOD &&
1334 epoll_ctl(timer_th.event_fd, EPOLL_CTL_ADD, fd, &event) == 0) {
1335 break;
1336 }
1337 e->registered = false;
1338 return false;
1339 case EEXIST:
1340 // Likewise in the other direction.
1341 if (op == EPOLL_CTL_ADD &&
1342 epoll_ctl(timer_th.event_fd, EPOLL_CTL_MOD, fd, &event) == 0) {
1343 break;
1344 }
1345 return false;
1346 case EBADF:
1347 case EPERM:
1348 // closed, or the fd does not support epoll
1349 e->registered = false;
1350 return false;
1351 default:
1352 perror("epoll_ctl");
1353 rb_bug("fd_waiters_arm/epoll_ctl failed (fd:%d op:%d errno:%d)", fd, op, errno);
1354 }
1355 }
1356 e->registered = true;
1357#else
1358# error "neither kqueue nor epoll"
1359#endif
1360
1361 e->armed_flags = want;
1362 return true;
1363}
1364
1365static bool
1366fd_ready_nonblock(int fd, short events)
1367{
1368 struct pollfd pfd = {
1369 .fd = fd,
1370 .events = events,
1371 };
1372
1373 // A "ready" answer makes the caller report the requested event, so a
1374 // closed fd (POLLNVAL) must not count: it owes the caller EBADF.
1375 return poll(&pfd, 1, 0) > 0 && !(pfd.revents & POLLNVAL);
1376}
1377
1378static void
1379verify_waiting_list(void)
1380{
1381#if VM_CHECK_MODE > 0
1382 struct rb_thread_sched_waiting *w;
1383
1384 for (int lvl = 0; lvl < TIMER_WHEEL_LEVELS; lvl++) {
1385 const struct timer_wheel_level *lv = &timer_th.wheel[lvl];
1386
1387 for (int slot = 0; slot < TIMER_WHEEL_SLOTS; slot++) {
1388 bool occupied = (lv->occupied >> slot) & 1;
1389 VM_ASSERT(occupied == !ccan_list_empty(&lv->slots[slot]));
1390
1391 ccan_list_for_each(&lv->slots[slot], w, node) {
1392 // an io entry's flags belong to its fd shard: do not read them here
1393 if (!(w->flags & FD_WAIT_IO_MASK)) {
1394 VM_ASSERT(w->flags & thread_sched_waiting_timeout);
1395 VM_ASSERT(w->data.timeout != 0);
1396 }
1397 VM_ASSERT(w->wheel_lvl == lvl);
1398 VM_ASSERT(w->wheel_slot == slot);
1399 }
1400 }
1401 }
1402#endif
1403}
1404
1405/* ------------------------------------------------------------------------
1406 * backend: the readiness notification mechanism (epoll / kqueue).
1407 *
1408 * Everything below that names epoll or kqueue is this backend; the rest of
1409 * the M:N scheduler only asks it to arm an fd (fd_waiters_arm) and to wait
1410 * for what fired (event_wait / timer_thread_polling).
1411 * ------------------------------------------------------------------------ */
1412
1413#if HAVE_SYS_EVENT_H // kqueue helpers
1414
1415static enum thread_sched_waiting_flag
1416kqueue_translate_filter_to_flags(int16_t filter)
1417{
1418 switch (filter) {
1419 case EVFILT_READ:
1420 return thread_sched_waiting_io_read;
1421 case EVFILT_WRITE:
1422 return thread_sched_waiting_io_write;
1423 case EVFILT_TIMER:
1424 return thread_sched_waiting_timeout;
1425 default:
1426 rb_bug("kevent filter:%d not supported", filter);
1427 }
1428}
1429
1430static int
1431kqueue_wait(rb_vm_t *vm)
1432{
1433 struct timespec calculated_timeout;
1434 struct timespec *timeout = NULL;
1435 int timeout_ms = timer_thread_set_timeout(vm);
1436
1437 if (timeout_ms > 0) {
1438 calculated_timeout.tv_sec = timeout_ms / 1000;
1439 calculated_timeout.tv_nsec = (timeout_ms % 1000) * 1000000;
1440 timeout = &calculated_timeout;
1441 }
1442 else if (timeout_ms == 0) {
1443 // Relying on the absence of other members of struct timespec is not strictly portable,
1444 // and kevent needs a 0-valued timespec to mean immediate timeout.
1445 memset(&calculated_timeout, 0, sizeof(struct timespec));
1446 timeout = &calculated_timeout;
1447 }
1448
1449 return kevent(timer_th.event_fd, NULL, 0, timer_th.finished_events, KQUEUE_EVENTS_MAX, timeout);
1450}
1451
1452static void
1453kqueue_create(void)
1454{
1455 if ((timer_th.event_fd = kqueue()) == -1) rb_bug("kqueue creation failed (errno:%d)", errno);
1456 int flags = fcntl(timer_th.event_fd, F_GETFD);
1457 if (flags == -1) {
1458 rb_bug("kqueue GETFD failed (errno:%d)", errno);
1459 }
1460
1461 flags |= FD_CLOEXEC;
1462 if (fcntl(timer_th.event_fd, F_SETFD, flags) == -1) {
1463 rb_bug("kqueue SETFD failed (errno:%d)", errno);
1464 }
1465}
1466
1467#endif // HAVE_SYS_EVENT_H
1468
1469// return false if the fd is not waitable or not need to wait.
1470static enum timer_thread_register_result
1471timer_thread_register_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags, rb_hrtime_t *rel, uint32_t event_serial)
1472{
1473 RUBY_DEBUG_LOG("th:%u fd:%d flag:%d rel:%lu", rb_th_serial(th), fd, flags, rel ? (unsigned long)*rel : 0);
1474
1475 VM_ASSERT(th == NULL || TH_SCHED(th)->running == th);
1476 VM_ASSERT(flags != 0);
1477
1478 rb_hrtime_t abs = 0; // 0 means no timeout
1479
1480 if (rel) {
1481 if (*rel > 0) {
1482 flags |= thread_sched_waiting_timeout;
1483 }
1484 else {
1485 return timer_thread_already_ready; // zero timeout: nothing to wait for
1486 }
1487 }
1488
1489 if (flags & thread_sched_waiting_timeout) {
1490 VM_ASSERT(rel != NULL);
1491 abs = rb_hrtime_add(rb_hrtime_now(), *rel);
1492 }
1493
1494 if (flags & thread_sched_waiting_io_read) {
1495 if (!(flags & thread_sched_waiting_io_force) && fd_ready_nonblock(fd, POLLIN)) {
1496 RUBY_DEBUG_LOG("fd readable");
1497 return timer_thread_already_ready;
1498 }
1499 VM_ASSERT(fd >= 0);
1500 }
1501
1502 if (flags & thread_sched_waiting_io_write) {
1503 if (!(flags & thread_sched_waiting_io_force) && fd_ready_nonblock(fd, POLLOUT)) {
1504 RUBY_DEBUG_LOG("fd writable");
1505 return timer_thread_already_ready;
1506 }
1507 VM_ASSERT(fd >= 0);
1508 }
1509
1510 if (flags & FD_WAIT_IO_MASK) {
1511 fd_shard_lock(fd);
1512 {
1513 struct rb_fd_waiters *e = fd_waiters_lookup(fd, true);
1514
1515 if (e == NULL) { // fd beyond the map: fall back to a blocking wait
1516 fd_shard_unlock(fd);
1517 return timer_thread_unavailable;
1518 }
1519
1520 // Arm the union of what this fd's waiters want, so a second waiter
1521 // on the same fd extends the arming instead of colliding with it.
1522 if (!fd_waiters_arm(fd, e, fd_waiters_union(e) | (uint32_t)(flags & FD_WAIT_IO_MASK), false)) {
1523 fd_shard_unlock(fd);
1524 return timer_thread_unavailable;
1525 }
1526
1527 if (th) {
1528 ccan_list_add_tail(&e->waiters, &th->sched.waiting_reason.fd_node);
1529
1530 VM_ASSERT(th->sched.waiting_reason.flags == thread_sched_waiting_none);
1531 th->sched.waiting_reason.flags = flags;
1532 th->sched.waiting_reason.data.timeout = abs;
1533 th->sched.waiting_reason.data.fd = fd;
1534 th->sched.waiting_reason.data.result = 0;
1535 th->sched.waiting_reason.data.event_serial = event_serial;
1536
1537 if (abs != 0) {
1538 RUBY_DEBUG_LOG("abs:%lu", (unsigned long)abs);
1539 VM_ASSERT(flags & thread_sched_waiting_timeout);
1540
1541 rb_native_mutex_lock(&timer_th.waiting_lock);
1542 {
1543 rb_hrtime_t prev_expiry = timer_th.next_expiry;
1544 timer_wheel_insert(&th->sched.waiting_reason);
1545 verify_waiting_list();
1546 if (timer_th.next_expiry < prev_expiry) {
1547 // an earlier deadline than the timer thread is armed for
1548 timer_thread_wakeup_force();
1549 }
1550 }
1551 rb_native_mutex_unlock(&timer_th.waiting_lock);
1552 }
1553 }
1554 RUBY_DEBUG_LOG("armed fd:%d want:%u", fd, e->armed_flags);
1555 }
1556 fd_shard_unlock(fd);
1557 }
1558 else if (th) {
1559 // fd-less timed wait: the wheel lock owns it end to end
1560 VM_ASSERT(abs != 0 && (flags & thread_sched_waiting_timeout));
1561
1562 rb_native_mutex_lock(&timer_th.waiting_lock);
1563 {
1564 VM_ASSERT(th->sched.waiting_reason.flags == thread_sched_waiting_none);
1565 th->sched.waiting_reason.flags = flags;
1566 th->sched.waiting_reason.data.timeout = abs;
1567 th->sched.waiting_reason.data.fd = fd;
1568 th->sched.waiting_reason.data.result = 0;
1569 th->sched.waiting_reason.data.event_serial = event_serial;
1570
1571 rb_hrtime_t prev_expiry = timer_th.next_expiry;
1572 timer_wheel_insert(&th->sched.waiting_reason);
1573 verify_waiting_list();
1574 if (timer_th.next_expiry < prev_expiry) {
1575 timer_thread_wakeup_force();
1576 }
1577 }
1578 rb_native_mutex_unlock(&timer_th.waiting_lock);
1579 }
1580 else {
1581 VM_ASSERT(abs == 0);
1582 }
1583
1584 return timer_thread_registered;
1585}
1586
1587// Drop `th` from its fd's waiter list and re-arm the backend for whoever is
1588// left. The fd's shard lock must be held.
1589static void
1590timer_thread_unregister_waiting(rb_thread_t *th, int fd, enum thread_sched_waiting_flag flags)
1591{
1592 if (!(th->sched.waiting_reason.flags & FD_WAIT_IO_MASK)) {
1593 return;
1594 }
1595
1596 RUBY_DEBUG_LOG("th:%u fd:%d", rb_th_serial(th), fd);
1597
1598 ccan_list_del_init(&th->sched.waiting_reason.fd_node);
1599
1600 struct rb_fd_waiters *e = fd_waiters_lookup(fd, false);
1601 if (e) {
1602 fd_waiters_arm(fd, e, fd_waiters_union(e), false);
1603 }
1604}
1605
1606// The timer thread's own wakeup pipe has no waiter: it stays armed forever and
1607// is recognised by its fd when an event arrives.
1608static void
1609timer_thread_arm_comm_pipe(void)
1610{
1611 int fd = timer_th.comm_fds[0];
1612
1613#if HAVE_SYS_EVENT_H
1614 struct kevent ke;
1615 EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, (void *)(uintptr_t)fd_event_tag(fd, 0));
1616 if (kevent(timer_th.event_fd, &ke, 1, NULL, 0, NULL) == -1) {
1617 rb_bug("timer_thread_arm_comm_pipe/kevent failed (errno:%d)", errno);
1618 }
1619#elif HAVE_SYS_EPOLL_H
1620 struct epoll_event event = {
1621 .events = EPOLLIN,
1622 .data = { .u64 = fd_event_tag(fd, 0) },
1623 };
1624 if (epoll_ctl(timer_th.event_fd, EPOLL_CTL_ADD, fd, &event) == -1) {
1625 rb_bug("timer_thread_arm_comm_pipe/epoll_ctl failed (errno:%d)", errno);
1626 }
1627#else
1628# error "neither kqueue nor epoll"
1629#endif
1630}
1631
1632static void
1633timer_thread_setup_mn(void)
1634{
1635#if HAVE_SYS_EVENT_H
1636 kqueue_create();
1637 RUBY_DEBUG_LOG("kqueue_fd:%d", timer_th.event_fd);
1638#else
1639 if ((timer_th.event_fd = epoll_create1(EPOLL_CLOEXEC)) == -1) rb_bug("epoll_create (errno:%d)", errno);
1640 RUBY_DEBUG_LOG("epoll_fd:%d", timer_th.event_fd);
1641#endif
1642 RUBY_DEBUG_LOG("comm_fds:%d/%d", timer_th.comm_fds[0], timer_th.comm_fds[1]);
1643
1644 timer_thread_arm_comm_pipe();
1645}
1646
1647static int
1648event_wait(rb_vm_t *vm)
1649{
1650#if HAVE_SYS_EVENT_H
1651 int r = kqueue_wait(vm);
1652#else
1653 int r = epoll_wait(timer_th.event_fd, timer_th.finished_events, EPOLL_EVENTS_MAX, timer_thread_set_timeout(vm));
1654#endif
1655 return r;
1656}
1657
1658// How many waiters one pass may unlink before it stops holding waiting_lock.
1659#define FD_WAKE_BATCH 16
1660
1661
1662// Deliver an fd event to every thread waiting for it. Waiters are unlinked
1663// under waiting_lock but woken after releasing it (the scheduler lock is taken
1664// before it, never after); event_serial, captured under the lock, guards them.
1665static void
1666timer_thread_wake_fd_waiters(int fd, uint32_t generation, uint32_t wake_flags, int result)
1667{
1668 struct timer_wake batch[FD_WAKE_BATCH];
1669
1670 if (wake_flags == 0) return;
1671
1672 while (1) {
1673 int n = 0;
1674 bool more = false;
1675
1676 fd_shard_lock(fd);
1677 {
1678 struct rb_fd_waiters *e = fd_waiters_lookup(fd, false);
1679
1680 // A newer generation means the fd was disarmed after this event was
1681 // queued, and the number may name a different file by now.
1682 if (e != NULL && e->generation == generation) {
1683 struct rb_thread_sched_waiting *w, *nxt;
1684
1685 ccan_list_for_each_safe(&e->waiters, w, nxt, fd_node) {
1686 if (!(w->flags & wake_flags)) continue;
1687
1688 if (n == FD_WAKE_BATCH) {
1689 more = true;
1690 break;
1691 }
1692
1693 ccan_list_del_init(&w->fd_node);
1694
1695 if (w->flags & thread_sched_waiting_timeout) {
1696 // also leaves the timer wheel (or the expiry pass's
1697 // batch, whose claim will then find the flags gone)
1698 rb_native_mutex_lock(&timer_th.waiting_lock);
1699 timer_wheel_del(w);
1700 rb_native_mutex_unlock(&timer_th.waiting_lock);
1701 }
1702
1703 // The pin must be visible before the flags clear: a waiter
1704 // that sees the clear may skip parking, finish and die,
1705 // and the fence only waits on the pending count.
1706 batch[n].th = thread_sched_waiting_thread(w);
1707 batch[n].serial = w->data.event_serial;
1708 timer_wake_pending_inc(batch[n].th);
1709 n++;
1710
1711 w->flags = thread_sched_waiting_none;
1712 w->data.fd = -1;
1713 w->data.result = result;
1714 }
1715
1716 // Re-arm for whoever is still waiting on this fd (nothing, if
1717 // they all just woke up).
1718 fd_waiters_arm(fd, e, fd_waiters_union(e), true);
1719 }
1720 }
1721 fd_shard_unlock(fd);
1722
1723 for (int i = 0; i < n; i++) {
1724 timer_thread_wakeup_thread(batch[i].th, batch[i].serial);
1725 }
1726 timer_wake_pending_clear(batch, n);
1727
1728 if (!more) break;
1729 }
1730}
1731
1732/*
1733 * The purpose of the timer thread:
1734 *
1735 * (1) Periodic checking
1736 * (1-1) Provide time slice for active NTs
1737 * (1-2) Check NT shortage
1738 * (1-3) Periodic UBF (global)
1739 * (1-4) Lazy GRQ deq start
1740 * (2) Receive notification
1741 * (2-1) async I/O termination
1742 * (2-2) timeout
1743 * (2-2-1) sleep(n)
1744 * (2-2-2) timeout(n), I/O, ...
1745 */
1746static void
1747timer_thread_polling(rb_vm_t *vm)
1748{
1749 int r = event_wait(vm);
1750
1751 RUBY_DEBUG_LOG("r:%d errno:%d", r, errno);
1752
1753 switch (r) {
1754 case 0: // timeout
1755 RUBY_DEBUG_LOG("timeout%s", "");
1756
1757 ractor_sched_lock(vm, NULL);
1758 {
1759 // (1-1) timeslice
1760 timer_thread_check_timeslice(vm);
1761
1762 // (1-4) lazy grq deq
1763 if (vm->ractor.sched.grq_cnt > 0) {
1764 RUBY_DEBUG_LOG("GRQ cnt: %u", vm->ractor.sched.grq_cnt);
1765 rb_native_cond_signal(&vm->ractor.sched.cond);
1766 }
1767 }
1768 ractor_sched_unlock(vm, NULL);
1769
1770 // (1-2)
1771 native_thread_check_and_create_shared(vm);
1772
1773 break;
1774
1775 case -1:
1776 switch (errno) {
1777 case EINTR:
1778 // simply retry
1779 break;
1780 default:
1781 perror("event_wait");
1782 rb_bug("event_wait errno:%d", errno);
1783 }
1784 break;
1785
1786 default:
1787 RUBY_DEBUG_LOG("%d event(s)", r);
1788
1789#if HAVE_SYS_EVENT_H
1790 for (int i=0; i<r; i++) {
1791 uint64_t tag = (uint64_t)(uintptr_t)timer_th.finished_events[i].udata;
1792 int fd = (int)timer_th.finished_events[i].ident;
1793 int16_t filter = timer_th.finished_events[i].filter;
1794
1795 if (fd == timer_th.comm_fds[0]) {
1796 RUBY_DEBUG_LOG("comm from fd:%d", timer_th.comm_fds[1]);
1797 consume_communication_pipe(timer_th.comm_fds[0]);
1798 continue;
1799 }
1800
1801 uint32_t wake_flags = kqueue_translate_filter_to_flags(filter) & FD_WAIT_IO_MASK;
1802 if (timer_th.finished_events[i].flags & (EV_EOF | EV_ERROR)) {
1803 wake_flags = FD_WAIT_IO_MASK; // end of file or error concerns everyone
1804 }
1805
1806 timer_thread_wake_fd_waiters(fd, FD_EVENT_TAG_GEN(tag), wake_flags, filter);
1807 }
1808#elif HAVE_SYS_EPOLL_H
1809 for (int i=0; i<r; i++) {
1810 uint64_t tag = timer_th.finished_events[i].data.u64;
1811 int fd = FD_EVENT_TAG_FD(tag);
1812 uint32_t events = timer_th.finished_events[i].events;
1813
1814 if (fd == timer_th.comm_fds[0]) {
1815 RUBY_DEBUG_LOG("comm from fd:%d", timer_th.comm_fds[1]);
1816 consume_communication_pipe(timer_th.comm_fds[0]);
1817 continue;
1818 }
1819
1820 RUBY_DEBUG_LOG("io event. fd:%d event:%s%s%s%s%s%s", fd,
1821 (events & EPOLLIN) ? "in/" : "",
1822 (events & EPOLLOUT) ? "out/" : "",
1823 (events & EPOLLRDHUP) ? "RDHUP/" : "",
1824 (events & EPOLLPRI) ? "pri/" : "",
1825 (events & EPOLLERR) ? "err/" : "",
1826 (events & EPOLLHUP) ? "hup/" : "");
1827
1828 uint32_t wake_flags = 0;
1829 if (events & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) wake_flags |= thread_sched_waiting_io_read;
1830 if (events & EPOLLOUT) wake_flags |= thread_sched_waiting_io_write;
1831 // An error or hangup ends every wait on this fd, in either direction.
1832 if (events & (EPOLLERR | EPOLLHUP)) wake_flags |= FD_WAIT_IO_MASK;
1833
1834 timer_thread_wake_fd_waiters(fd, FD_EVENT_TAG_GEN(tag), wake_flags, (int)events);
1835 }
1836#else
1837# error "neither kqueue nor epoll"
1838#endif
1839 }
1840}
1841
1842#endif // HAVE_SYS_EPOLL_H || HAVE_SYS_EVENT_H
1843
1844#else // USE_MN_THREADS
1845
1846static void
1847timer_thread_setup_mn(void)
1848{
1849 // do nothing
1850}
1851
1852static void
1853timer_thread_polling(rb_vm_t *vm)
1854{
1855 int timeout = timer_thread_set_timeout(vm);
1856
1857 struct pollfd pfd = {
1858 .fd = timer_th.comm_fds[0],
1859 .events = POLLIN,
1860 };
1861
1862 int r = poll(&pfd, 1, timeout);
1863
1864 switch (r) {
1865 case 0: // timeout
1866 ractor_sched_lock(vm, NULL);
1867 {
1868 // (1-1) timeslice
1869 timer_thread_check_timeslice(vm);
1870 }
1871 ractor_sched_unlock(vm, NULL);
1872 break;
1873
1874 case -1: // error
1875 switch (errno) {
1876 case EINTR:
1877 // simply retry
1878 break;
1879 default:
1880 perror("poll");
1881 rb_bug("poll errno:%d", errno);
1882 break;
1883 }
1884
1885 case 1:
1886 consume_communication_pipe(timer_th.comm_fds[0]);
1887 break;
1888
1889 default:
1890 rb_bug("unreachbale");
1891 }
1892}
1893
1894static int
1895native_thread_create_shared(rb_thread_t *th)
1896{
1897 rb_bug("unreachable");
1898}
1899
1900static enum thread_sched_wait_result
1901thread_sched_wait_events(struct rb_thread_sched *sched, rb_thread_t *th, int fd, enum thread_sched_waiting_flag events, rb_hrtime_t *rel)
1902{
1903 rb_bug("unreachable");
1904}
1905
1906// Without the wheel every thread is dedicated, so a Ractor wait takes its
1907// deadline on its own condvar and never reaches these.
1908static bool
1909ractor_sched_timeout_arm(rb_thread_t *th, const rb_hrtime_t *rel)
1910{
1911 rb_bug("unreachable");
1912}
1913
1914static bool
1915ractor_sched_timeout_disarm(rb_thread_t *th)
1916{
1917 rb_bug("unreachable");
1918}
1919
1920static int
1921timer_wheel_timeout(int timeout)
1922{
1923 return timeout; // no M:N threads, no timed waiters
1924}
1925
1926static void
1927timer_thread_wake_fence(rb_thread_t *th)
1928{
1929 // no timer wheel, no wake batches
1930}
1931
1932static void
1933timer_thread_check_timeout(rb_vm_t *vm)
1934{
1935 // no M:N threads, no timed waiters
1936}
1937
1938#endif // USE_MN_THREADS
#define RUBY_ATOMIC_PTR_LOAD(var)
Identical to RUBY_ATOMIC_LOAD, except it expects its arguments are void*.
Definition atomic.h:348
#define RUBY_ATOMIC_INC(var)
Atomically increments the value pointed by var.
Definition atomic.h:214
#define RUBY_ATOMIC_PTR_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are void*.
Definition atomic.h:375
#define RUBY_ATOMIC_CAS(var, oldval, newval)
Atomic compare-and-swap.
Definition atomic.h:165
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_DEC(var)
Atomically decrements the value pointed by var.
Definition atomic.h:223
#define RUBY_ATOMIC_LOAD(var)
Atomic load.
Definition atomic.h:175
#define RUBY_ATOMIC_PTR_SET(var, val)
Identical to RUBY_ATOMIC_SET, except it expects its arguments are void*.
Definition atomic.h:361
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
int len
Length of the buffer.
Definition io.h:8
#define RUBY_INTERNAL_THREAD_EVENT_RESUMED
Triggered when a thread successfully acquired the GVL.
Definition thread.h:249
#define RUBY_INTERNAL_THREAD_EVENT_SUSPENDED
Triggered when a thread released the GVL.
Definition thread.h:256
#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_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_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.
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40