Ruby 3.5.0dev (2025-05-21 revision 97e774b95d5233f801666f873c27de64684b0cf0)
mmtk.c
1#include <pthread.h>
2#include <stdbool.h>
3
4#include "ruby/assert.h"
5#include "ruby/atomic.h"
6#include "ruby/debug.h"
7
8#include "gc/gc.h"
9#include "gc/gc_impl.h"
10#include "gc/mmtk/mmtk.h"
11
12#include "ccan/list/list.h"
13#include "darray.h"
14
15#ifdef __APPLE__
16#include <sys/sysctl.h>
17#endif
18
19struct objspace {
20 bool measure_gc_time;
21 bool gc_stress;
22
23 size_t gc_count;
24 size_t total_gc_time;
25 size_t total_allocated_objects;
26
27 st_table *finalizer_table;
28 struct MMTk_final_job *finalizer_jobs;
29 rb_postponed_job_handle_t finalizer_postponed_job;
30
31 struct ccan_list_head ractor_caches;
32 unsigned long live_ractor_cache_count;
33
34 pthread_mutex_t mutex;
35 bool world_stopped;
36 pthread_cond_t cond_world_stopped;
37 pthread_cond_t cond_world_started;
38 size_t start_the_world_count;
39
40 struct rb_gc_vm_context vm_context;
41};
42
44 struct ccan_list_node list_node;
45
46 MMTk_Mutator *mutator;
47 bool gc_mutator_p;
48};
49
51 struct MMTk_final_job *next;
52 enum {
53 MMTK_FINAL_JOB_DFREE,
54 MMTK_FINAL_JOB_FINALIZE,
55 } kind;
56 union {
57 struct {
58 void (*func)(void *);
59 void *data;
60 } dfree;
61 struct {
62 /* HACK: we store the object ID on the 0th element of this array. */
63 VALUE finalizer_array;
64 } finalize;
65 } as;
66};
67
68#ifdef RB_THREAD_LOCAL_SPECIFIER
69RB_THREAD_LOCAL_SPECIFIER struct MMTk_GCThreadTLS *rb_mmtk_gc_thread_tls;
70#else
71# error We currently need language-supported TLS
72#endif
73
74#include <pthread.h>
75
76static void
77rb_mmtk_init_gc_worker_thread(MMTk_VMWorkerThread gc_thread_tls)
78{
79 rb_mmtk_gc_thread_tls = gc_thread_tls;
80}
81
82static bool
83rb_mmtk_is_mutator(void)
84{
85 return ruby_native_thread_p();
86}
87
88static void
89rb_mmtk_stop_the_world(void)
90{
91 struct objspace *objspace = rb_gc_get_objspace();
92
93 int err;
94 if ((err = pthread_mutex_lock(&objspace->mutex)) != 0) {
95 rb_bug("ERROR: cannot lock objspace->mutex: %s", strerror(err));
96 }
97
98 while (!objspace->world_stopped) {
99 pthread_cond_wait(&objspace->cond_world_stopped, &objspace->mutex);
100 }
101
102 if ((err = pthread_mutex_unlock(&objspace->mutex)) != 0) {
103 rb_bug("ERROR: cannot release objspace->mutex: %s", strerror(err));
104 }
105}
106
107static void
108rb_mmtk_resume_mutators(void)
109{
110 struct objspace *objspace = rb_gc_get_objspace();
111
112 int err;
113 if ((err = pthread_mutex_lock(&objspace->mutex)) != 0) {
114 rb_bug("ERROR: cannot lock objspace->mutex: %s", strerror(err));
115 }
116
117 objspace->world_stopped = false;
118 objspace->gc_count++;
119 pthread_cond_broadcast(&objspace->cond_world_started);
120
121 if ((err = pthread_mutex_unlock(&objspace->mutex)) != 0) {
122 rb_bug("ERROR: cannot release objspace->mutex: %s", strerror(err));
123 }
124}
125
126static void
127rb_mmtk_block_for_gc(MMTk_VMMutatorThread mutator)
128{
129 struct objspace *objspace = rb_gc_get_objspace();
130
131 size_t starting_gc_count = objspace->gc_count;
132 int lock_lev = rb_gc_vm_lock();
133 int err;
134 if ((err = pthread_mutex_lock(&objspace->mutex)) != 0) {
135 rb_bug("ERROR: cannot lock objspace->mutex: %s", strerror(err));
136 }
137
138 if (objspace->gc_count == starting_gc_count) {
139 rb_gc_event_hook(0, RUBY_INTERNAL_EVENT_GC_START);
140
141 rb_gc_initialize_vm_context(&objspace->vm_context);
142
143 mutator->gc_mutator_p = true;
144
145 struct timespec gc_start_time;
146 if (objspace->measure_gc_time) {
147 clock_gettime(CLOCK_MONOTONIC, &gc_start_time);
148 }
149
150 rb_gc_save_machine_context();
151
152 rb_gc_vm_barrier();
153
154 objspace->world_stopped = true;
155
156 pthread_cond_broadcast(&objspace->cond_world_stopped);
157
158 // Wait for GC end
159 while (objspace->world_stopped) {
160 pthread_cond_wait(&objspace->cond_world_started, &objspace->mutex);
161 }
162
163 if (objspace->measure_gc_time) {
164 struct timespec gc_end_time;
165 clock_gettime(CLOCK_MONOTONIC, &gc_end_time);
166
167 objspace->total_gc_time +=
168 (gc_end_time.tv_sec - gc_start_time.tv_sec) * (1000 * 1000 * 1000) +
169 (gc_end_time.tv_nsec - gc_start_time.tv_nsec);
170 }
171 }
172
173 if ((err = pthread_mutex_unlock(&objspace->mutex)) != 0) {
174 rb_bug("ERROR: cannot release objspace->mutex: %s", strerror(err));
175 }
176 rb_gc_vm_unlock(lock_lev);
177}
178
179static size_t
180rb_mmtk_number_of_mutators(void)
181{
182 struct objspace *objspace = rb_gc_get_objspace();
183 return objspace->live_ractor_cache_count;
184}
185
186static void
187rb_mmtk_get_mutators(void (*visit_mutator)(MMTk_Mutator *mutator, void *data), void *data)
188{
189 struct objspace *objspace = rb_gc_get_objspace();
190 struct MMTk_ractor_cache *ractor_cache;
191
192 ccan_list_for_each(&objspace->ractor_caches, ractor_cache, list_node) {
193 visit_mutator(ractor_cache->mutator, data);
194 }
195}
196
197static void
198rb_mmtk_scan_gc_roots(void)
199{
200 struct objspace *objspace = rb_gc_get_objspace();
201
202 // FIXME: Make `rb_gc_mark_roots` aware that the current thread may not have EC.
203 // See: https://github.com/ruby/mmtk/issues/22
204 rb_gc_worker_thread_set_vm_context(&objspace->vm_context);
205 rb_gc_mark_roots(objspace, NULL);
206 rb_gc_worker_thread_unset_vm_context(&objspace->vm_context);
207}
208
209static int
210pin_value(st_data_t key, st_data_t value, st_data_t data)
211{
212 rb_gc_impl_mark_and_pin((void *)data, (VALUE)value);
213
214 return ST_CONTINUE;
215}
216
217static void
218rb_mmtk_scan_objspace(void)
219{
220 struct objspace *objspace = rb_gc_get_objspace();
221
222 if (objspace->finalizer_table != NULL) {
223 st_foreach(objspace->finalizer_table, pin_value, (st_data_t)objspace);
224 }
225
226 struct MMTk_final_job *job = objspace->finalizer_jobs;
227 while (job != NULL) {
228 switch (job->kind) {
229 case MMTK_FINAL_JOB_DFREE:
230 break;
231 case MMTK_FINAL_JOB_FINALIZE:
232 rb_gc_impl_mark(objspace, job->as.finalize.finalizer_array);
233 break;
234 default:
235 rb_bug("rb_mmtk_scan_objspace: unknown final job type %d", job->kind);
236 }
237
238 job = job->next;
239 }
240}
241
242static void
243rb_mmtk_scan_object_ruby_style(MMTk_ObjectReference object)
244{
245 rb_gc_mark_children(rb_gc_get_objspace(), (VALUE)object);
246}
247
248static void
249rb_mmtk_call_gc_mark_children(MMTk_ObjectReference object)
250{
251 rb_gc_mark_children(rb_gc_get_objspace(), (VALUE)object);
252}
253
254static void
255rb_mmtk_call_obj_free(MMTk_ObjectReference object)
256{
257 VALUE obj = (VALUE)object;
258 struct objspace *objspace = rb_gc_get_objspace();
259
260 if (RB_UNLIKELY(rb_gc_event_hook_required_p(RUBY_INTERNAL_EVENT_FREEOBJ))) {
261 rb_gc_worker_thread_set_vm_context(&objspace->vm_context);
262 rb_gc_event_hook(obj, RUBY_INTERNAL_EVENT_FREEOBJ);
263 rb_gc_worker_thread_unset_vm_context(&objspace->vm_context);
264 }
265
266 rb_gc_obj_free(objspace, obj);
267}
268
269static size_t
270rb_mmtk_vm_live_bytes(void)
271{
272 return 0;
273}
274
275static void
276make_final_job(struct objspace *objspace, VALUE obj, VALUE table)
277{
279 RUBY_ASSERT(mmtk_is_reachable((MMTk_ObjectReference)table));
281
283
284 struct MMTk_final_job *job = xmalloc(sizeof(struct MMTk_final_job));
285 job->next = objspace->finalizer_jobs;
286 job->kind = MMTK_FINAL_JOB_FINALIZE;
287 job->as.finalize.finalizer_array = table;
288
289 objspace->finalizer_jobs = job;
290}
291
292static int
293rb_mmtk_update_finalizer_table_i(st_data_t key, st_data_t value, st_data_t data)
294{
296 RUBY_ASSERT(mmtk_is_reachable((MMTk_ObjectReference)value));
298
299 struct objspace *objspace = (struct objspace *)data;
300
301 if (!mmtk_is_reachable((MMTk_ObjectReference)key)) {
302 make_final_job(objspace, (VALUE)key, (VALUE)value);
303
304 rb_postponed_job_trigger(objspace->finalizer_postponed_job);
305
306 return ST_DELETE;
307 }
308
309 return ST_CONTINUE;
310}
311
312static void
313rb_mmtk_update_finalizer_table(void)
314{
315 struct objspace *objspace = rb_gc_get_objspace();
316
317 // TODO: replace with st_foreach_with_replace when GC is moving
318 st_foreach(objspace->finalizer_table, rb_mmtk_update_finalizer_table_i, (st_data_t)objspace);
319}
320
321static int
322rb_mmtk_update_table_i(VALUE val, void *data)
323{
324 if (!mmtk_is_reachable((MMTk_ObjectReference)val)) {
325 return ST_DELETE;
326 }
327
328 return ST_CONTINUE;
329}
330
331static int
332rb_mmtk_global_tables_count(void)
333{
334 return RB_GC_VM_WEAK_TABLE_COUNT;
335}
336
337static void
338rb_mmtk_update_global_tables(int table)
339{
340 RUBY_ASSERT(table < RB_GC_VM_WEAK_TABLE_COUNT);
341
342 rb_gc_vm_weak_table_foreach(rb_mmtk_update_table_i, NULL, NULL, true, (enum rb_gc_vm_weak_tables)table);
343}
344
345// Bootup
346MMTk_RubyUpcalls ruby_upcalls = {
347 rb_mmtk_init_gc_worker_thread,
348 rb_mmtk_is_mutator,
349 rb_mmtk_stop_the_world,
350 rb_mmtk_resume_mutators,
351 rb_mmtk_block_for_gc,
352 rb_mmtk_number_of_mutators,
353 rb_mmtk_get_mutators,
354 rb_mmtk_scan_gc_roots,
355 rb_mmtk_scan_objspace,
356 rb_mmtk_scan_object_ruby_style,
357 rb_mmtk_call_gc_mark_children,
358 rb_mmtk_call_obj_free,
359 rb_mmtk_vm_live_bytes,
360 rb_mmtk_update_global_tables,
361 rb_mmtk_global_tables_count,
362 rb_mmtk_update_finalizer_table,
363};
364
365// Use max 80% of the available memory by default for MMTk
366#define RB_MMTK_HEAP_LIMIT_PERC 80
367#define RB_MMTK_DEFAULT_HEAP_MIN (1024 * 1024)
368#define RB_MMTK_DEFAULT_HEAP_MAX (rb_mmtk_system_physical_memory() / 100 * RB_MMTK_HEAP_LIMIT_PERC)
369
370enum mmtk_heap_mode {
371 RB_MMTK_DYNAMIC_HEAP,
372 RB_MMTK_FIXED_HEAP
373};
374
375MMTk_Builder *
376rb_mmtk_builder_init(void)
377{
378 MMTk_Builder *builder = mmtk_builder_default();
379 return builder;
380}
381
382void *
383rb_gc_impl_objspace_alloc(void)
384{
385 MMTk_Builder *builder = rb_mmtk_builder_init();
386 mmtk_init_binding(builder, NULL, &ruby_upcalls, (MMTk_ObjectReference)Qundef);
387
388 return calloc(1, sizeof(struct objspace));
389}
390
391static void gc_run_finalizers(void *data);
392
393void
394rb_gc_impl_objspace_init(void *objspace_ptr)
395{
396 struct objspace *objspace = objspace_ptr;
397
398 objspace->measure_gc_time = true;
399
400 objspace->finalizer_table = st_init_numtable();
401 objspace->finalizer_postponed_job = rb_postponed_job_preregister(0, gc_run_finalizers, objspace);
402
403 ccan_list_head_init(&objspace->ractor_caches);
404
405 objspace->mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
406 objspace->cond_world_stopped = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
407 objspace->cond_world_started = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
408}
409
410void
411rb_gc_impl_objspace_free(void *objspace_ptr)
412{
413 free(objspace_ptr);
414}
415
416void *
417rb_gc_impl_ractor_cache_alloc(void *objspace_ptr, void *ractor)
418{
419 struct objspace *objspace = objspace_ptr;
420 if (objspace->live_ractor_cache_count == 0) {
421 mmtk_initialize_collection(ractor);
422 }
423 objspace->live_ractor_cache_count++;
424
425 struct MMTk_ractor_cache *cache = malloc(sizeof(struct MMTk_ractor_cache));
426 ccan_list_add(&objspace->ractor_caches, &cache->list_node);
427
428 cache->mutator = mmtk_bind_mutator(cache);
429
430 return cache;
431}
432
433void
434rb_gc_impl_ractor_cache_free(void *objspace_ptr, void *cache_ptr)
435{
436 struct objspace *objspace = objspace_ptr;
437 struct MMTk_ractor_cache *cache = cache_ptr;
438
439 ccan_list_del(&cache->list_node);
440
441 RUBY_ASSERT(objspace->live_ractor_cache_count > 1);
442 objspace->live_ractor_cache_count--;
443
444 mmtk_destroy_mutator(cache->mutator);
445}
446
447void rb_gc_impl_set_params(void *objspace_ptr) { }
448
449static VALUE gc_verify_internal_consistency(VALUE self) { return Qnil; }
450
451void
452rb_gc_impl_init(void)
453{
454 VALUE gc_constants = rb_hash_new();
455 rb_hash_aset(gc_constants, ID2SYM(rb_intern("BASE_SLOT_SIZE")), SIZET2NUM(sizeof(VALUE) * 5));
456 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OVERHEAD")), INT2NUM(0));
457 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVARGC_MAX_ALLOCATE_SIZE")), LONG2FIX(640));
458 // Pretend we have 5 size pools
459 rb_hash_aset(gc_constants, ID2SYM(rb_intern("SIZE_POOL_COUNT")), LONG2FIX(5));
460 OBJ_FREEZE(gc_constants);
461 rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
462
463 // no-ops for compatibility
464 rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency, 0);
465
469 rb_define_singleton_method(rb_mGC, "latest_compact_info", rb_f_notimplement, 0);
470 rb_define_singleton_method(rb_mGC, "verify_compaction_references", rb_f_notimplement, -1);
471}
472
473static size_t heap_sizes[6] = {
474 40, 80, 160, 320, 640, 0
475};
476
477size_t *
478rb_gc_impl_heap_sizes(void *objspace_ptr)
479{
480 return heap_sizes;
481}
482
483int
484rb_mmtk_obj_free_iter_wrapper(VALUE obj, void *data)
485{
486 struct objspace *objspace = data;
487
488 if (!RB_TYPE_P(obj, T_NONE)) {
489 rb_gc_obj_free_vm_weak_references(obj);
490 rb_gc_obj_free(objspace, obj);
491 }
492
493 return 0;
494}
495
496// Shutdown
497static void each_object(struct objspace *objspace, int (*func)(VALUE, void *), void *data);
498
499void
500rb_gc_impl_shutdown_free_objects(void *objspace_ptr)
501{
502 mmtk_set_gc_enabled(false);
503 each_object(objspace_ptr, rb_mmtk_obj_free_iter_wrapper, objspace_ptr);
504 mmtk_set_gc_enabled(true);
505}
506
507// GC
508void
509rb_gc_impl_start(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact)
510{
511 mmtk_handle_user_collection_request(rb_gc_get_ractor_newobj_cache(), true, full_mark);
512}
513
514bool
515rb_gc_impl_during_gc_p(void *objspace_ptr)
516{
517 // TODO
518 return false;
519}
520
521static void
522rb_gc_impl_prepare_heap_i(MMTk_ObjectReference obj, void *d)
523{
524 rb_gc_prepare_heap_process_object((VALUE)obj);
525}
526
527void
528rb_gc_impl_prepare_heap(void *objspace_ptr)
529{
530 mmtk_enumerate_objects(rb_gc_impl_prepare_heap_i, NULL);
531}
532
533void
534rb_gc_impl_gc_enable(void *objspace_ptr)
535{
536 mmtk_set_gc_enabled(true);
537}
538
539void
540rb_gc_impl_gc_disable(void *objspace_ptr, bool finish_current_gc)
541{
542 mmtk_set_gc_enabled(false);
543}
544
545bool
546rb_gc_impl_gc_enabled_p(void *objspace_ptr)
547{
548 return mmtk_gc_enabled_p();
549}
550
551void
552rb_gc_impl_stress_set(void *objspace_ptr, VALUE flag)
553{
554 struct objspace *objspace = objspace_ptr;
555
556 objspace->gc_stress = RTEST(flag);
557}
558
559VALUE
560rb_gc_impl_stress_get(void *objspace_ptr)
561{
562 struct objspace *objspace = objspace_ptr;
563
564 return objspace->gc_stress ? Qtrue : Qfalse;
565}
566
567VALUE
568rb_gc_impl_config_get(void *objspace_ptr)
569{
570 VALUE hash = rb_hash_new();
571
572 rb_hash_aset(hash, ID2SYM(rb_intern_const("mmtk_worker_count")), RB_ULONG2NUM(mmtk_worker_count()));
573 rb_hash_aset(hash, ID2SYM(rb_intern_const("mmtk_plan")), rb_str_new_cstr((const char *)mmtk_plan()));
574 rb_hash_aset(hash, ID2SYM(rb_intern_const("mmtk_heap_mode")), rb_str_new_cstr((const char *)mmtk_heap_mode()));
575 size_t heap_min = mmtk_heap_min();
576 if (heap_min > 0) rb_hash_aset(hash, ID2SYM(rb_intern_const("mmtk_heap_min")), RB_ULONG2NUM(heap_min));
577 rb_hash_aset(hash, ID2SYM(rb_intern_const("mmtk_heap_max")), RB_ULONG2NUM(mmtk_heap_max()));
578
579 return hash;
580}
581
582void
583rb_gc_impl_config_set(void *objspace_ptr, VALUE hash)
584{
585 // TODO
586}
587
588// Object allocation
589
590VALUE
591rb_gc_impl_new_obj(void *objspace_ptr, void *cache_ptr, VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, bool wb_protected, size_t alloc_size)
592{
593#define MMTK_ALLOCATION_SEMANTICS_DEFAULT 0
594 struct objspace *objspace = objspace_ptr;
595 struct MMTk_ractor_cache *ractor_cache = cache_ptr;
596
597 if (alloc_size > 640) rb_bug("too big");
598 for (int i = 0; i < 5; i++) {
599 if (alloc_size == heap_sizes[i]) break;
600 if (alloc_size < heap_sizes[i]) {
601 alloc_size = heap_sizes[i];
602 break;
603 }
604 }
605
606 if (objspace->gc_stress) {
607 mmtk_handle_user_collection_request(ractor_cache, false, false);
608 }
609
610 VALUE *alloc_obj = mmtk_alloc(ractor_cache->mutator, alloc_size + 8, MMTk_MIN_OBJ_ALIGN, 0, MMTK_ALLOCATION_SEMANTICS_DEFAULT);
611 alloc_obj++;
612 alloc_obj[-1] = alloc_size;
613 alloc_obj[0] = flags;
614 alloc_obj[1] = klass;
615 if (alloc_size > 16) alloc_obj[2] = v1;
616 if (alloc_size > 24) alloc_obj[3] = v2;
617 if (alloc_size > 32) alloc_obj[4] = v3;
618
619 mmtk_post_alloc(ractor_cache->mutator, (void*)alloc_obj, alloc_size + 8, MMTK_ALLOCATION_SEMANTICS_DEFAULT);
620
621 // TODO: only add when object needs obj_free to be called
622 mmtk_add_obj_free_candidate(alloc_obj);
623
624 objspace->total_allocated_objects++;
625
626 return (VALUE)alloc_obj;
627}
628
629size_t
630rb_gc_impl_obj_slot_size(VALUE obj)
631{
632 return ((VALUE *)obj)[-1];
633}
634
635size_t
636rb_gc_impl_heap_id_for_size(void *objspace_ptr, size_t size)
637{
638 for (int i = 0; i < 5; i++) {
639 if (size == heap_sizes[i]) return i;
640 if (size < heap_sizes[i]) return i;
641 }
642
643 rb_bug("size too big");
644}
645
646bool
647rb_gc_impl_size_allocatable_p(size_t size)
648{
649 return size <= 640;
650}
651
652// Malloc
653void *
654rb_gc_impl_malloc(void *objspace_ptr, size_t size)
655{
656 // TODO: don't use system malloc
657 return malloc(size);
658}
659
660void *
661rb_gc_impl_calloc(void *objspace_ptr, size_t size)
662{
663 // TODO: don't use system calloc
664 return calloc(1, size);
665}
666
667void *
668rb_gc_impl_realloc(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size)
669{
670 // TODO: don't use system realloc
671 return realloc(ptr, new_size);
672}
673
674void
675rb_gc_impl_free(void *objspace_ptr, void *ptr, size_t old_size)
676{
677 // TODO: don't use system free
678 free(ptr);
679}
680
681void rb_gc_impl_adjust_memory_usage(void *objspace_ptr, ssize_t diff) { }
682
683// Marking
684void
685rb_gc_impl_mark(void *objspace_ptr, VALUE obj)
686{
687 if (RB_SPECIAL_CONST_P(obj)) return;
688
689 rb_mmtk_gc_thread_tls->object_closure.c_function(rb_mmtk_gc_thread_tls->object_closure.rust_closure,
690 rb_mmtk_gc_thread_tls->gc_context,
691 (MMTk_ObjectReference)obj,
692 false);
693}
694
695void
696rb_gc_impl_mark_and_move(void *objspace_ptr, VALUE *ptr)
697{
698 if (RB_SPECIAL_CONST_P(*ptr)) return;
699
700 // TODO: make it movable
701 rb_gc_impl_mark(objspace_ptr, *ptr);
702}
703
704void
705rb_gc_impl_mark_and_pin(void *objspace_ptr, VALUE obj)
706{
707 if (RB_SPECIAL_CONST_P(obj)) return;
708
709 // TODO: also pin
710 rb_gc_impl_mark(objspace_ptr, obj);
711}
712
713void
714rb_gc_impl_mark_maybe(void *objspace_ptr, VALUE obj)
715{
716 if (rb_gc_impl_pointer_to_heap_p(objspace_ptr, (const void *)obj)) {
717 rb_gc_impl_mark_and_pin(objspace_ptr, obj);
718 }
719}
720
721void
722rb_gc_impl_mark_weak(void *objspace_ptr, VALUE *ptr)
723{
724 mmtk_mark_weak((MMTk_ObjectReference *)ptr);
725}
726
727void
728rb_gc_impl_remove_weak(void *objspace_ptr, VALUE parent_obj, VALUE *ptr)
729{
730 mmtk_remove_weak((MMTk_ObjectReference *)ptr);
731}
732
733// Compaction
734bool
735rb_gc_impl_object_moved_p(void *objspace_ptr, VALUE obj)
736{
737 rb_bug("unimplemented");
738}
739
740VALUE
741rb_gc_impl_location(void *objspace_ptr, VALUE value)
742{
743 rb_bug("unimplemented");
744}
745
746// Write barriers
747void
748rb_gc_impl_writebarrier(void *objspace_ptr, VALUE a, VALUE b)
749{
750 struct MMTk_ractor_cache *cache = rb_gc_get_ractor_newobj_cache();
751
752 mmtk_object_reference_write_post(cache->mutator, (MMTk_ObjectReference)a);
753}
754
755void
756rb_gc_impl_writebarrier_unprotect(void *objspace_ptr, VALUE obj)
757{
758 mmtk_register_wb_unprotected_object((MMTk_ObjectReference)obj);
759}
760
761void
762rb_gc_impl_writebarrier_remember(void *objspace_ptr, VALUE obj)
763{
764 struct MMTk_ractor_cache *cache = rb_gc_get_ractor_newobj_cache();
765
766 mmtk_object_reference_write_post(cache->mutator, (MMTk_ObjectReference)obj);
767}
768
769// Heap walking
770static void
771each_objects_i(MMTk_ObjectReference obj, void *d)
772{
773 rb_darray(VALUE) *objs = d;
774
775 rb_darray_append(objs, (VALUE)obj);
776}
777
778static void
779each_object(struct objspace *objspace, int (*func)(VALUE, void *), void *data)
780{
781 rb_darray(VALUE) objs;
782 rb_darray_make(&objs, 0);
783
784 mmtk_enumerate_objects(each_objects_i, &objs);
785
786 VALUE *obj_ptr;
787 rb_darray_foreach(objs, i, obj_ptr) {
788 if (!mmtk_is_mmtk_object((MMTk_ObjectReference)*obj_ptr)) continue;
789
790 if (func(*obj_ptr, data) != 0) {
791 break;
792 }
793 }
794
795 rb_darray_free(objs);
796}
797
799 int (*func)(void *, void *, size_t, void *);
800 void *data;
801};
802
803static int
804rb_gc_impl_each_objects_i(VALUE obj, void *d)
805{
806 struct rb_gc_impl_each_objects_data *data = d;
807
808 size_t slot_size = rb_gc_impl_obj_slot_size(obj);
809
810 return data->func((void *)obj, (void *)(obj + slot_size), slot_size, data->data);
811}
812
813void
814rb_gc_impl_each_objects(void *objspace_ptr, int (*func)(void *, void *, size_t, void *), void *data)
815{
816 struct rb_gc_impl_each_objects_data each_objects_data = {
817 .func = func,
818 .data = data
819 };
820
821 each_object(objspace_ptr, rb_gc_impl_each_objects_i, &each_objects_data);
822}
823
825 void (*func)(VALUE, void *);
826 void *data;
827};
828
829static int
830rb_gc_impl_each_object_i(VALUE obj, void *d)
831{
832 struct rb_gc_impl_each_object_data *data = d;
833
834 data->func(obj, data->data);
835
836 return 0;
837}
838
839void
840rb_gc_impl_each_object(void *objspace_ptr, void (*func)(VALUE, void *), void *data)
841{
842 struct rb_gc_impl_each_object_data each_object_data = {
843 .func = func,
844 .data = data
845 };
846
847 each_object(objspace_ptr, rb_gc_impl_each_object_i, &each_object_data);
848}
849
850// Finalizers
851static VALUE
852gc_run_finalizers_get_final(long i, void *data)
853{
854 VALUE table = (VALUE)data;
855
856 return RARRAY_AREF(table, i + 1);
857}
858
859static void
860gc_run_finalizers(void *data)
861{
862 struct objspace *objspace = data;
863
864 rb_gc_set_pending_interrupt();
865
866 while (objspace->finalizer_jobs != NULL) {
867 struct MMTk_final_job *job = objspace->finalizer_jobs;
868 objspace->finalizer_jobs = job->next;
869
870 switch (job->kind) {
871 case MMTK_FINAL_JOB_DFREE:
872 job->as.dfree.func(job->as.dfree.data);
873 break;
874 case MMTK_FINAL_JOB_FINALIZE: {
875 VALUE finalizer_array = job->as.finalize.finalizer_array;
876
877 rb_gc_run_obj_finalizer(
878 RARRAY_AREF(finalizer_array, 0),
879 RARRAY_LEN(finalizer_array) - 1,
880 gc_run_finalizers_get_final,
881 (void *)finalizer_array
882 );
883
884 RB_GC_GUARD(finalizer_array);
885 break;
886 }
887 }
888
889 xfree(job);
890 }
891
892 rb_gc_unset_pending_interrupt();
893}
894
895void
896rb_gc_impl_make_zombie(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data)
897{
898 if (dfree == NULL) return;
899
900 struct objspace *objspace = objspace_ptr;
901
902 struct MMTk_final_job *job = xmalloc(sizeof(struct MMTk_final_job));
903 job->kind = MMTK_FINAL_JOB_DFREE;
904 job->as.dfree.func = dfree;
905 job->as.dfree.data = data;
906
907 struct MMTk_final_job *prev;
908 do {
909 job->next = objspace->finalizer_jobs;
910 prev = RUBY_ATOMIC_PTR_CAS(objspace->finalizer_jobs, job->next, job);
911 } while (prev != job->next);
912
913 if (!ruby_free_at_exit_p()) {
914 rb_postponed_job_trigger(objspace->finalizer_postponed_job);
915 }
916}
917
918VALUE
919rb_gc_impl_define_finalizer(void *objspace_ptr, VALUE obj, VALUE block)
920{
921 struct objspace *objspace = objspace_ptr;
922 VALUE table;
923 st_data_t data;
924
925 RBASIC(obj)->flags |= FL_FINALIZE;
926
927 int lev = rb_gc_vm_lock();
928
929 if (st_lookup(objspace->finalizer_table, obj, &data)) {
930 table = (VALUE)data;
931
932 /* avoid duplicate block, table is usually small */
933 {
934 long len = RARRAY_LEN(table);
935 long i;
936
937 for (i = 0; i < len; i++) {
938 VALUE recv = RARRAY_AREF(table, i);
939 if (rb_equal(recv, block)) {
940 rb_gc_vm_unlock(lev);
941 return recv;
942 }
943 }
944 }
945
946 rb_ary_push(table, block);
947 }
948 else {
949 table = rb_ary_new3(2, block);
950 rb_obj_hide(table);
951 st_add_direct(objspace->finalizer_table, obj, table);
952 }
953
954 rb_gc_vm_unlock(lev);
955
956 return block;
957}
958
959void
960rb_gc_impl_undefine_finalizer(void *objspace_ptr, VALUE obj)
961{
962 struct objspace *objspace = objspace_ptr;
963
964 st_data_t data = obj;
965
966 int lev = rb_gc_vm_lock();
967 st_delete(objspace->finalizer_table, &data, 0);
968 rb_gc_vm_unlock(lev);
969
970 FL_UNSET(obj, FL_FINALIZE);
971}
972
973void
974rb_gc_impl_copy_finalizer(void *objspace_ptr, VALUE dest, VALUE obj)
975{
976 struct objspace *objspace = objspace_ptr;
977 VALUE table;
978 st_data_t data;
979
980 if (!FL_TEST(obj, FL_FINALIZE)) return;
981
982 int lev = rb_gc_vm_lock();
983 if (RB_LIKELY(st_lookup(objspace->finalizer_table, obj, &data))) {
984 table = rb_ary_dup((VALUE)data);
985 RARRAY_ASET(table, 0, rb_obj_id(dest));
986 st_insert(objspace->finalizer_table, dest, table);
987 FL_SET(dest, FL_FINALIZE);
988 }
989 else {
990 rb_bug("rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
991 }
992 rb_gc_vm_unlock(lev);
993}
994
995static int
996move_finalizer_from_table_i(st_data_t key, st_data_t val, st_data_t arg)
997{
998 struct objspace *objspace = (struct objspace *)arg;
999
1000 make_final_job(objspace, (VALUE)key, (VALUE)val);
1001
1002 return ST_DELETE;
1003}
1004
1005void
1006rb_gc_impl_shutdown_call_finalizer(void *objspace_ptr)
1007{
1008 struct objspace *objspace = objspace_ptr;
1009
1010 while (objspace->finalizer_table->num_entries) {
1011 st_foreach(objspace->finalizer_table, move_finalizer_from_table_i, (st_data_t)objspace);
1012
1013 gc_run_finalizers(objspace);
1014 }
1015
1016 struct MMTk_RawVecOfObjRef registered_candidates = mmtk_get_all_obj_free_candidates();
1017 for (size_t i = 0; i < registered_candidates.len; i++) {
1018 VALUE obj = (VALUE)registered_candidates.ptr[i];
1019
1020 if (rb_gc_shutdown_call_finalizer_p(obj)) {
1021 rb_gc_obj_free(objspace_ptr, obj);
1022 RBASIC(obj)->flags = 0;
1023 }
1024 }
1025 mmtk_free_raw_vec_of_obj_ref(registered_candidates);
1026
1027 gc_run_finalizers(objspace);
1028}
1029
1030// Forking
1031
1032void
1033rb_gc_impl_before_fork(void *objspace_ptr)
1034{
1035 mmtk_before_fork();
1036}
1037
1038void
1039rb_gc_impl_after_fork(void *objspace_ptr, rb_pid_t pid)
1040{
1041 mmtk_after_fork(rb_gc_get_ractor_newobj_cache());
1042}
1043
1044// Statistics
1045
1046void
1047rb_gc_impl_set_measure_total_time(void *objspace_ptr, VALUE flag)
1048{
1049 struct objspace *objspace = objspace_ptr;
1050
1051 objspace->measure_gc_time = RTEST(flag);
1052}
1053
1054bool
1055rb_gc_impl_get_measure_total_time(void *objspace_ptr)
1056{
1057 struct objspace *objspace = objspace_ptr;
1058
1059 return objspace->measure_gc_time;
1060}
1061
1062unsigned long long
1063rb_gc_impl_get_total_time(void *objspace_ptr)
1064{
1065 struct objspace *objspace = objspace_ptr;
1066
1067 return objspace->total_gc_time;
1068}
1069
1070size_t
1071rb_gc_impl_gc_count(void *objspace_ptr)
1072{
1073 struct objspace *objspace = objspace_ptr;
1074
1075 return objspace->gc_count;
1076}
1077
1078VALUE
1079rb_gc_impl_latest_gc_info(void *objspace_ptr, VALUE hash_or_key)
1080{
1081 VALUE hash = Qnil, key = Qnil;
1082
1083 if (SYMBOL_P(hash_or_key)) {
1084 key = hash_or_key;
1085 }
1086 else if (RB_TYPE_P(hash_or_key, T_HASH)) {
1087 hash = hash_or_key;
1088 }
1089 else {
1090 rb_bug("gc_info_decode: non-hash or symbol given");
1091 }
1092
1093#define SET(name, attr) \
1094 if (key == ID2SYM(rb_intern_const(#name))) \
1095 return (attr); \
1096 else if (hash != Qnil) \
1097 rb_hash_aset(hash, ID2SYM(rb_intern_const(#name)), (attr));
1098
1099 /* Hack to get StackProf working because it calls rb_gc_latest_gc_info with
1100 * the :state key and expects a result. This always returns the :none state. */
1101 SET(state, ID2SYM(rb_intern_const("none")));
1102#undef SET
1103
1104 if (!NIL_P(key)) {
1105 // Matched key should return above
1106 return Qundef;
1107 }
1108
1109 return hash;
1110}
1111
1112enum gc_stat_sym {
1113 gc_stat_sym_count,
1114 gc_stat_sym_time,
1115 gc_stat_sym_total_allocated_objects,
1116 gc_stat_sym_total_bytes,
1117 gc_stat_sym_used_bytes,
1118 gc_stat_sym_free_bytes,
1119 gc_stat_sym_starting_heap_address,
1120 gc_stat_sym_last_heap_address,
1121 gc_stat_sym_last
1122};
1123
1124static VALUE gc_stat_symbols[gc_stat_sym_last];
1125
1126static void
1127setup_gc_stat_symbols(void)
1128{
1129 if (gc_stat_symbols[0] == 0) {
1130#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
1131 S(count);
1132 S(time);
1133 S(total_allocated_objects);
1134 S(total_bytes);
1135 S(used_bytes);
1136 S(free_bytes);
1137 S(starting_heap_address);
1138 S(last_heap_address);
1139 }
1140}
1141
1142VALUE
1143rb_gc_impl_stat(void *objspace_ptr, VALUE hash_or_sym)
1144{
1145 struct objspace *objspace = objspace_ptr;
1146 VALUE hash = Qnil, key = Qnil;
1147
1148 setup_gc_stat_symbols();
1149
1150 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
1151 hash = hash_or_sym;
1152 }
1153 else if (SYMBOL_P(hash_or_sym)) {
1154 key = hash_or_sym;
1155 }
1156 else {
1157 rb_bug("non-hash or symbol given");
1158 }
1159
1160#define SET(name, attr) \
1161 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
1162 return SIZET2NUM(attr); \
1163 else if (hash != Qnil) \
1164 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
1165
1166 SET(count, objspace->gc_count);
1167 SET(time, objspace->total_gc_time / (1000 * 1000));
1168 SET(total_allocated_objects, objspace->total_allocated_objects);
1169 SET(total_bytes, mmtk_total_bytes());
1170 SET(used_bytes, mmtk_used_bytes());
1171 SET(free_bytes, mmtk_free_bytes());
1172 SET(starting_heap_address, (size_t)mmtk_starting_heap_address());
1173 SET(last_heap_address, (size_t)mmtk_last_heap_address());
1174#undef SET
1175
1176 if (!NIL_P(key)) {
1177 // Matched key should return above
1178 return Qundef;
1179 }
1180
1181 return hash;
1182}
1183
1184VALUE
1185rb_gc_impl_stat_heap(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym)
1186{
1187 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
1188 return hash_or_sym;
1189 }
1190 else {
1191 return Qundef;
1192 }
1193}
1194
1195// Miscellaneous
1196
1197#define RB_GC_OBJECT_METADATA_ENTRY_COUNT 1
1198static struct rb_gc_object_metadata_entry object_metadata_entries[RB_GC_OBJECT_METADATA_ENTRY_COUNT + 1];
1199
1201rb_gc_impl_object_metadata(void *objspace_ptr, VALUE obj)
1202{
1203 static ID ID_object_id;
1204
1205 if (!ID_object_id) {
1206#define I(s) ID_##s = rb_intern(#s);
1207 I(object_id);
1208#undef I
1209 }
1210
1211 size_t n = 0;
1212
1213#define SET_ENTRY(na, v) do { \
1214 RUBY_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
1215 object_metadata_entries[n].name = ID_##na; \
1216 object_metadata_entries[n].val = v; \
1217 n++; \
1218} while (0)
1219
1220 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
1221
1222 object_metadata_entries[n].name = 0;
1223 object_metadata_entries[n].val = 0;
1224
1225 return object_metadata_entries;
1226}
1227
1228bool
1229rb_gc_impl_pointer_to_heap_p(void *objspace_ptr, const void *ptr)
1230{
1231 if (ptr == NULL) return false;
1232 if ((uintptr_t)ptr % sizeof(void*) != 0) return false;
1233 return mmtk_is_mmtk_object((MMTk_Address)ptr);
1234}
1235
1236bool
1237rb_gc_impl_garbage_object_p(void *objspace_ptr, VALUE obj)
1238{
1239 return false;
1240}
1241
1242void rb_gc_impl_set_event_hook(void *objspace_ptr, const rb_event_flag_t event) { }
1243
1244void
1245rb_gc_impl_copy_attributes(void *objspace_ptr, VALUE dest, VALUE obj)
1246{
1247 if (mmtk_object_wb_unprotected_p((MMTk_ObjectReference)obj)) {
1248 rb_gc_impl_writebarrier_unprotect(objspace_ptr, dest);
1249 }
1250
1251 rb_gc_impl_copy_finalizer(objspace_ptr, dest, obj);
1252}
1253
1254// GC Identification
1255
1256const char *
1257rb_gc_impl_active_gc_name(void)
1258{
1259 return "mmtk";
1260}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Atomic operations.
#define RUBY_ATOMIC_PTR_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are void*.
Definition atomic.h:340
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
unsigned int rb_postponed_job_handle_t
The type of a handle returned from rb_postponed_job_preregister and passed to rb_postponed_job_trigge...
Definition debug.h:703
void rb_postponed_job_trigger(rb_postponed_job_handle_t h)
Triggers a pre-registered job registered with rb_postponed_job_preregister, scheduling it for executi...
Definition vm_trace.c:1784
rb_postponed_job_handle_t rb_postponed_job_preregister(unsigned int flags, rb_postponed_job_func_t func, void *data)
Pre-registers a func in Ruby's postponed job preregistration table, returning an opaque handle which ...
Definition vm_trace.c:1750
#define RUBY_INTERNAL_EVENT_FREEOBJ
Object swept.
Definition event.h:94
#define RUBY_INTERNAL_EVENT_GC_START
GC started.
Definition event.h:95
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
static VALUE RB_FL_TEST(VALUE obj, VALUE flags)
Tests if the given flag(s) are set or not.
Definition fl_type.h:482
static void RB_FL_UNSET(VALUE obj, VALUE flags)
Clears the given flag(s).
Definition fl_type.h:668
@ RUBY_FL_FINALIZE
This flag has something to do with finalisers.
Definition fl_type.h:238
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:134
#define T_NONE
Old name of RUBY_T_NONE.
Definition value_type.h:74
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FL_FINALIZE
Old name of RUBY_FL_FINALIZE.
Definition fl_type.h:61
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:128
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:130
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:132
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:104
VALUE rb_mGC
GC module.
Definition gc.c:435
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:179
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1514
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:573
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
int len
Length of the buffer.
Definition io.h:8
#define RB_ULONG2NUM
Just another name of rb_ulong2num_inline.
Definition long.h:59
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:386
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
Definition thread.c:5623
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
C99 shim for <stdbool.h>
void * rust_closure
The pointer to the Rust-level closure object.
Definition mmtk.h:45
MMTk_ObjectClosureFunction c_function
The function to be called from C.
Definition mmtk.h:41
Definition gc_impl.h:15
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
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376