Ruby 4.1.0dev (2026-09-26 revision b49347c28a15c475eba951ce426564647aeeacf0)
ractor_core.h (b49347c28a15c475eba951ce426564647aeeacf0)
1#ifndef RUBY_RACTOR_CORE_H
2#define RUBY_RACTOR_CORE_H
3#include "internal/gc.h"
4#include "internal/sanitizers.h"
5#include "ruby/ruby.h"
6#include "ruby/ractor.h"
7#include "vm_core.h"
8#include "id_table.h"
9#include "vm_debug.h"
10#include "hrtime.h"
11
12#ifndef RACTOR_CHECK_MODE
13#define RACTOR_CHECK_MODE (VM_CHECK_MODE || RUBY_DEBUG) && (SIZEOF_UINT64_T == SIZEOF_VALUE)
14#endif
15
16/* Record the registration-time VALUE in each rb_gc_register_address entry so the
17 * verifier can distinguish a transitioned cross-Ractor store from conservative
18 * garbage. Debug and ASAN builds only; production keeps one-word entries. */
19#ifndef RB_GC_REGISTERED_ADDR_CHECK
20# if RUBY_DEBUG || defined(RUBY_ASAN_ENABLED)
21# define RB_GC_REGISTERED_ADDR_CHECK 1
22# else
23# define RB_GC_REGISTERED_ADDR_CHECK 0
24# endif
25#endif
26
27// experimental flag because it is not sure it is the common pattern
28#define RUBY_TYPED_FROZEN_SHAREABLE_NO_REC RUBY_FL_FINALIZE
29
30/* An in-flight move payload, serialized off-heap (defined in ractor.c). */
32
34 // ractor lock
35 rb_nativethread_lock_t lock;
36
37#if RACTOR_CHECK_MODE > 0
38 VALUE locked_by;
39#endif
40
41 // incoming messages
42 struct ractor_queue *recv_queue;
43
44 // waiting threads for receiving
45 struct ccan_list_head waiters;
46
47 // ports
48 VALUE default_port_value;
49 struct st_table *ports;
50 size_t next_port_id;
51
52 /* The baskets this Ractor holds that are on no queue: one it is building to send,
53 * and one it has taken off a queue and is materializing. A queued basket is rooted
54 * by its queue instead. Only the owner touches this list. */
55 struct ccan_list_head off_queue_baskets;
56
57 // monitors
58 struct ccan_list_head monitors;
59
60 // value
61 rb_ractor_t *successor;
62 VALUE legacy;
63 bool legacy_exc;
64 bool legacy_taken; /* Ractor#value already returned the value */
65};
66
67struct ractor_basket;
68
69// created
70// | ready to run
71// ====================== inserted to vm->ractor
72// v
73// blocking <---+ all threads are blocking
74// | |
75// v |
76// running -----+
77// | all threads are terminated.
78// ====================== removed from vm->ractor
79// v
80// terminated
81//
82// status is protected by VM lock (global state)
83enum ractor_status {
84 ractor_created,
85 ractor_running,
86 ractor_blocking,
87 ractor_terminated,
88};
89
91 VALUE *addr;
92#if RB_GC_REGISTERED_ADDR_CHECK
93 /* A raw provenance snapshot for verification only. Never mark or dereference it. */
94 VALUE initial_value;
95#endif
96};
97
99 struct rb_ractor_pub pub;
100 struct rb_ractor_sync sync;
101
102 /* rb_gc_register_mark_object pins, per Ractor: the owner marks them (live via
103 * rb_ractor_mark_local_roots, unmerged zombie via the zombie scan) and a merge moves
104 * them to the survivor. Raw malloc, so a merge during sweep cannot re-enter GC. */
105 VALUE *registered_marks;
106 size_t registered_marks_cnt, registered_marks_capa;
107
108 struct rb_ractor_registered_addr *registered_addrs;
109 size_t registered_addrs_cnt, registered_addrs_capa;
110 bool registered_addrs_listed;
111
112 /* traversal-API mark redirect (NULL outside a traversal). Per Ractor so a
113 * concurrent traversal on another Ractor is never observed. A modular GC's
114 * Ractor-less marking worker threads read vm->gc.mark_func_data instead. */
115 struct gc_mark_func_data_struct *mark_func_data;
116
117 // thread management
118 struct {
119 struct ccan_list_head set;
120 unsigned int cnt;
121 unsigned int blocking_cnt;
122 unsigned int sleeper;
123 struct rb_thread_sched sched;
124 rb_execution_context_t *running_ec;
125 rb_thread_t *main;
126 // MN termination epilogue: keeps the dying thread marked (like a set
127 // member) between leaving the living set and its last use
128 rb_thread_t *dying_th;
129
130 // `main` is in rb_thread_terminate_all(), waiting for the others to go
131 bool terminating;
132 } threads;
133
134 /* Postponed jobs targeted at this Ractor
135 * (rb_postponed_job_trigger_for_ractor): bits index the VM-wide
136 * preregistration table; any of this Ractor's threads drains them
137 * in rb_postponed_job_flush. */
138 rb_atomic_t postponed_job_triggered_bits;
139
140 VALUE thgroup_default;
141
142 VALUE name;
143 VALUE loc;
144
145 enum ractor_status status_;
146
147 struct ccan_list_node vmlr_node;
148 bool in_terminated_set; /* vmlr_node is on vm->ractor.terminated_set */
149 /* The final self collection ran (ractor_postmortem_collect): from then on
150 * rb_ractor_mark_local_roots roots only the join value and the registered_marks
151 * pins, so the dying thread's own scaffolding can be collected. */
152 bool postmortem;
153
154 // ractor local data
155
156 rb_serial_t next_ec_serial;
157
158 st_table *local_storage;
159 struct rb_id_table *idkey_local_storage;
160 VALUE local_storage_store_lock;
161
162 /* 0 until first use: rb_ractor_stdin and friends build them lazily, with plain
163 * stores (rooted via ractor_mark_unshareable_parts; a write barrier on the
164 * shareable wrapper would shref-pin them). */
165 VALUE r_stdin;
166 VALUE r_stdout;
167 VALUE r_stderr;
168 VALUE verbose;
169 VALUE debug;
170
171 bool malloc_gc_disabled;
172 bool main_ractor;
173 void *newobj_cache;
174
175 /* This Ractor's objspace. The main Ractor receives the boot objspace from
176 * rb_gc_init_objspaces; a non-main Ractor shares the main one until it gets its
177 * own (while this is NULL). */
178 void *objspace;
179
180 /* A child Ractor's objspace is populated (Thread/Fiber wrappers) before it joins
181 * vm->ractor.set, so a whole-VM walk would miss it. Park it here from wrapper
182 * allocation until vm_insert_ractor clears it (under the VM lock) so the global GC
183 * still enumerates it. */
184 void *creating_child_objspace;
185
186}; // rb_ractor_t is defined in vm_core.h
187
188/* Mark the GC roots held in Ractor r's C structs (from the root scan in gc.c). */
189void rb_ractor_mark_local_roots(rb_ractor_t *r);
190void rb_ractor_mark_terminated_join_value(rb_ractor_t *r);
191void rb_ractor_reap_dead_ports(rb_ractor_t *r);
192
193/* Move src's registered_marks to dst and leave src empty (on join or when an orphan
194 * is absorbed). An absorb can run during a GC sweep, so the implementation uses raw
195 * realloc (ractor.c). */
196void rb_ractor_absorb_registered_marks(rb_ractor_t *dst, rb_ractor_t *src);
197
198void rb_ractor_absorb_registered_addrs_without_gc(rb_ractor_t *dst, rb_ractor_t *src);
199
200enum ractor_wakeup_status {
201 wakeup_none,
202 wakeup_by_send,
203 wakeup_by_interrupt,
204 wakeup_by_close,
205};
206
208 enum ractor_wakeup_status wakeup_status;
209 rb_thread_t *th;
210 struct ccan_list_node node;
211 rb_atomic_t event_serial;
212
213 // absolute deadline for this wait, NULL when there is no timeout
214 const rb_hrtime_t *end;
215};
216
217static inline VALUE
218rb_ractor_self(const rb_ractor_t *r)
219{
220 return r->pub.self;
221}
222
223rb_ractor_t *rb_ractor_main_alloc(void);
224void rb_ractor_main_setup(rb_vm_t *vm, rb_ractor_t *main_ractor, rb_thread_t *main_thread);
225void rb_ractor_atexit(rb_execution_context_t *ec, VALUE result);
226void rb_ractor_atexit_exception(rb_execution_context_t *ec);
227void rb_ractor_teardown(rb_execution_context_t *ec);
228void rb_ractor_receive_parameters(rb_execution_context_t *ec, rb_ractor_t *g, int len, VALUE *ptr);
229void rb_ractor_send_parameters(rb_execution_context_t *ec, rb_ractor_t *g, VALUE args);
230void rb_ractor_setup_default_port(rb_ractor_t *r);
231
232VALUE rb_thread_create_ractor(rb_ractor_t *g, VALUE args, VALUE proc); // defined in thread.c
233
234int rb_ractor_living_thread_num(const rb_ractor_t *);
235VALUE rb_ractor_thread_list(void);
236bool rb_ractor_p(VALUE rv);
237
238void rb_ractor_living_threads_init(rb_ractor_t *r);
239void rb_ractor_living_threads_insert(rb_ractor_t *r, rb_thread_t *th);
240void rb_ractor_living_threads_remove(rb_ractor_t *r, rb_thread_t *th);
241
242/* The structs the final self collection swept while the dying thread still stood on
243 * them; that thread frees them at its very last step (rb_ractor_postmortem_free). */
245 struct rb_thread_struct *th;
246 struct rb_fiber_struct *fiber;
247};
248void rb_ractor_postmortem(rb_thread_t *th, struct rb_ractor_postmortem_frees *pf);
249void rb_ractor_postmortem_free(const struct rb_ractor_postmortem_frees *pf);
250void rb_ractor_cancel_creation(rb_ractor_t *r, rb_thread_t *th);
251void rb_ractor_blocking_threads_inc(rb_ractor_t *r, const char *file, int line); // TODO: file, line only for RUBY_DEBUG_LOG
252void rb_ractor_blocking_threads_dec(rb_ractor_t *r, const char *file, int line); // TODO: file, line only for RUBY_DEBUG_LOG
253
254void rb_ractor_vm_barrier_interrupt_running_thread(rb_ractor_t *r);
255void rb_ractor_terminate_interrupt_main_thread(rb_ractor_t *r);
256void rb_ractor_terminate_all(void);
257bool rb_ractor_main_p_(void);
258void rb_ractor_atfork(rb_vm_t *vm, rb_thread_t *th);
259void rb_ractor_terminate_atfork(rb_vm_t *vm, rb_ractor_t *th);
260VALUE rb_ractor_require(VALUE feature, bool silent);
261VALUE rb_ractor_autoload_load(VALUE space, ID id);
262
263VALUE rb_ractor_ensure_shareable(VALUE obj, VALUE name);
264st_table *rb_ractor_targeted_hooks(rb_ractor_t *cr);
265
266RUBY_SYMBOL_EXPORT_BEGIN
267void rb_ractor_finish_marking(bool full_mark);
268
269bool rb_ractor_shareable_p_continue(VALUE obj);
270
271// THIS FUNCTION SHOULD NOT CALL WHILE INCREMENTAL MARKING!!
272// This function is for T_DATA::free_func
273void rb_ractor_local_storage_delkey(rb_ractor_local_key_t key);
274
275RUBY_SYMBOL_EXPORT_END
276
277static inline bool
278rb_ractor_main_p(void)
279{
280 if (ruby_single_main_ractor) {
281 return true;
282 }
283 else {
284 return rb_ractor_main_p_();
285 }
286}
287
288static inline bool
289rb_ractor_status_p(rb_ractor_t *r, enum ractor_status status)
290{
291 return r->status_ == status;
292}
293
294static inline void
295rb_ractor_sleeper_threads_inc(rb_ractor_t *r)
296{
297 r->threads.sleeper++;
298}
299
300static inline void
301rb_ractor_sleeper_threads_dec(rb_ractor_t *r)
302{
303 r->threads.sleeper--;
304}
305
306static inline void
307rb_ractor_sleeper_threads_clear(rb_ractor_t *r)
308{
309 r->threads.sleeper = 0;
310}
311
312static inline int
313rb_ractor_sleeper_thread_num(rb_ractor_t *r)
314{
315 return r->threads.sleeper;
316}
317
318static inline void
319rb_ractor_thread_switch(rb_ractor_t *cr, rb_thread_t *th, bool always_reset)
320{
321 RUBY_DEBUG_LOG("th:%d->%u%s",
322 cr->threads.running_ec ? (int)rb_th_serial(cr->threads.running_ec->thread_ptr) : -1,
323 rb_th_serial(th), cr->threads.running_ec == th->ec ? " (same)" : "");
324
325 if (cr->threads.running_ec != th->ec || always_reset) {
326 th->running_time_us = 0;
327 }
328
329 if (cr->threads.running_ec != th->ec) {
330 if (0) {
331 ruby_debug_printf("rb_ractor_thread_switch ec:%p->%p\n",
332 (void *)cr->threads.running_ec, (void *)th->ec);
333 }
334 }
335 else {
336 return;
337 }
338
339 cr->threads.running_ec = th->ec;
340
341 VM_ASSERT(cr == GET_RACTOR());
342}
343
344#define rb_ractor_set_current_ec(cr, ec) rb_ractor_set_current_ec_(cr, ec, __FILE__, __LINE__)
345#ifdef RB_THREAD_LOCAL_SPECIFIER
346void rb_current_ec_set(rb_execution_context_t *ec);
347#endif
348
349static inline void
350rb_ractor_set_current_ec_(rb_ractor_t *cr, rb_execution_context_t *ec, const char *file, int line)
351{
352#ifdef RB_THREAD_LOCAL_SPECIFIER
353 rb_current_ec_set(ec);
354#else
355 native_tls_set(ruby_current_ec_key, ec);
356#endif
357 RUBY_DEBUG_LOG2(file, line, "ec:%p->%p", (void *)cr->threads.running_ec, (void *)ec);
358 VM_ASSERT(ec == NULL || cr->threads.running_ec != ec);
359 cr->threads.running_ec = ec;
360}
361
362void rb_vm_ractor_blocking_cnt_inc(rb_vm_t *vm, rb_ractor_t *cr, const char *file, int line);
363void rb_vm_ractor_blocking_cnt_dec(rb_vm_t *vm, rb_ractor_t *cr, const char *file, int line);
364
365static inline rb_serial_t
366rb_ractor_id(const rb_ractor_t *r)
367{
368 return r->pub.id;
369}
370
371static inline void
372rb_ractor_targeted_hooks_incr(rb_ractor_t *cr)
373{
374 cr->pub.targeted_hooks_cnt++;
375}
376
377static inline void
378rb_ractor_targeted_hooks_decr(rb_ractor_t *cr)
379{
380 RUBY_ASSERT(cr->pub.targeted_hooks_cnt > 0);
381 cr->pub.targeted_hooks_cnt--;
382}
383
384static inline unsigned int
385rb_ractor_targeted_hooks_cnt(rb_ractor_t *cr)
386{
387 return cr->pub.targeted_hooks_cnt;
388}
389
390#if RACTOR_CHECK_MODE > 0
391
392extern bool rb_ractor_ignore_belonging_flag;
393
394/* An object's owning Ractor is decided by the objspace its page belongs to
395 * (rb_gc_obj_foreign_p). Putting an unshareable object on the VM stack of anyone
396 * but its owner is a containment violation. */
397static inline VALUE
398rb_ractor_confirm_belonging(VALUE obj)
399{
400 if (rb_ractor_ignore_belonging_flag) return obj;
401 if (SPECIAL_CONST_P(obj) || RB_OBJ_SHAREABLE_P(obj)) return obj;
402
403 if (UNLIKELY(rb_gc_obj_foreign_p(obj))) {
404 rp(obj);
405 rb_bug("rb_ractor_confirm_belonging: unshareable object of another Ractor's objspace");
406 }
407 return obj;
408}
409
410static inline void
411rb_ractor_ignore_belonging(bool flag)
412{
413 rb_ractor_ignore_belonging_flag = flag;
414}
415
416#else
417#define rb_ractor_confirm_belonging(obj) obj
418#define rb_ractor_ignore_belonging(flag) (0)
419#endif
420
421#endif /* RUBY_RACTOR_CORE_H */
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
Definition st.h:79
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40