forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.rs
More file actions
1847 lines (1649 loc) · 64.8 KB
/
Copy pathheap.rs
File metadata and controls
1847 lines (1649 loc) · 64.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! ORCA-compatible per-actor heap allocator for Nulang.
//!
//! Stage A1 — Nulang v0.4 ORCA Garbage Collector
//!
//! This module provides a bump allocator backed by a contiguous memory block,
//! with per-size-class intrusive free lists for fast object reuse. Every
//! allocation carries an [`OrcaHeader`] that stores reference counts, GC
//! colour, type tag, and live-object linked-list pointers.
//!
//! # Design decisions
//!
//! * **Bump allocation** for speed on the fast path (most allocations).
//! * **Chained bump blocks** — when the active bump block is exhausted, a new
//! block is allocated and chained onto the heap instead of failing. Objects
//! never move (raw payload pointers are held in VM registers, foreign refs,
//! and JIT code), so growth must chain — never realloc/copy — the existing
//! block.
//! * **Size-class free lists** (Tiny → Huge) so that freed objects can be
//! reused without touching the bump pointer.
//! * **Large-object space (LOS)** — allocations whose total size exceeds the
//! largest size class (256 bytes) are individually allocated with the
//! global allocator instead of consuming the contiguous bump region, and
//! are reused on an exact-size match from the `Huge` free list.
//! * **Intrusive live list** — every live object is a node in a doubly-linked
//! list embedded in the header. This makes `iter_live_objects` O(live) and
//! avoids auxiliary hash maps or bitmaps.
//! * **8-byte alignment** is enforced for every allocation (header + payload).
//! * **Zero `actor_id` default** — the heap is created before the actor ID is
//! known; callers should invoke `set_actor_id` immediately after creation.
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/// Required alignment for every allocation (header + payload).
const ALIGN: usize = 8;
/// Number of discrete size classes.
const NUM_SIZE_CLASSES: usize = 5;
/// Total-size threshold (header + aligned payload) above which allocations
/// go to the large-object space instead of the bump region. Set just above
/// the largest size-class block (256 bytes), so exactly the `Huge` class
/// is served by the LOS.
const LOS_THRESHOLD: usize = 256;
// ---------------------------------------------------------------------------
// SizeClass
// ---------------------------------------------------------------------------
/// Size classification for heap objects.
///
/// Each class represents an upper bound on the *total* allocation size
/// (header + aligned payload). Free lists are bucketed by this class so
/// that reallocation of similarly-sized objects is cache-friendly.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeClass {
/// Up to 32 bytes total.
Tiny = 0,
/// 33–64 bytes total.
Small = 1,
/// 65–128 bytes total.
Medium = 2,
/// 129–256 bytes total.
Large = 3,
/// 257+ bytes total (unbounded).
Huge = 4,
}
impl SizeClass {}
/// Map a *total* allocation size (header + payload, already aligned) to its
/// size class and the rounded-up block size for free-list bucketing. The
/// bump allocator reserves the full block size for every allocation, so all
/// blocks in a class are physically uniform and freely interchangeable.
fn classify_total_size(total_size: usize) -> (SizeClass, usize) {
// Clamp to at least the header size so that even zero-payload
// allocations have a well-defined class.
let total_size = total_size.max(std::mem::size_of::<OrcaHeader>());
match total_size {
0..=32 => (SizeClass::Tiny, 32),
33..=64 => (SizeClass::Small, 64),
65..=128 => (SizeClass::Medium, 128),
129..=256 => (SizeClass::Large, 256),
n => (SizeClass::Huge, n),
}
}
// ---------------------------------------------------------------------------
// GcColor
// ---------------------------------------------------------------------------
/// Tri-colour marker used by the ORCA cycle detector.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GcColor {
/// Object is potentially garbage (not yet visited).
White = 0,
/// Object has been discovered but children not yet scanned.
Gray = 1,
/// Object and its transitive children are reachable.
Black = 2,
}
// ---------------------------------------------------------------------------
// TypeTag
// ---------------------------------------------------------------------------
/// Runtime type tag for heap-allocated objects.
///
/// The GC and the debugger use this to interpret payload layout.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeTag {
/// Reference to another actor (contains a `u64` actor id).
ActorRef = 0,
/// Dynamically-sized array.
Array = 1,
/// UTF-8 string data.
String = 2,
/// Record / object with named fields.
Record = 3,
/// Function closure (captures environment).
Closure = 4,
/// Hash map.
Map = 5,
/// Fixed-size tuple.
Tuple = 6,
/// Raw untyped data (FFI boundaries).
Raw = 7,
/// Remote actor reference (node_id + actor_id).
RemoteActor = 8,
}
// ---------------------------------------------------------------------------
// OrcaHeader
// ---------------------------------------------------------------------------
/// Header prepended to every heap allocation.
///
/// The header is laid out with `#[repr(C)]` so that the payload pointer
/// returned by [`ActorHeap::alloc`] is always exactly one `OrcaHeader`
/// stride past the header base address. [`ActorHeap::header_of`] recovers
/// the header by walking backward one stride.
///
/// # Memory layout ( verified by `test_header_size` )
///
/// ```text
/// offset | field
/// -------+---------------
/// 0 | ref_count (u32)
/// 4 | foreign_count (u32)
/// 8 | sticky (bool)
/// 9 | size_class (SizeClass u8)
/// 10 | gc_color (GcColor u8)
/// 11 | type_tag (TypeTag u8)
/// 12 | _pad ([u8; 4]) — aligns actor_id to 8 bytes
/// 16 | actor_id (u64)
/// 24 | size (usize — total bytes, header + aligned payload)
/// 32 | payload_size (usize — requested payload bytes)
/// 40 | live_next (*mut OrcaHeader)
/// 48 | live_prev (*mut OrcaHeader)
/// -------+---------------
/// 56 | TOTAL
/// ```
///
/// # Thread safety
///
/// The counts are **plain integers, not atomics**. The runtime is a
/// single-threaded synchronous coordinator: one scheduler thread runs all
/// actor steps, `process_gc_ops`, and cycle detection, and it is the only
/// thread that ever touches a heap. Network reader threads and LLM worker
/// threads never dereference an `OrcaHeader`. (The header was never
/// `Send`/`Sync` anyway — `live_next`/`live_prev` are raw pointers.)
#[repr(C)]
pub struct OrcaHeader {
/// Local reference count — how many references exist *inside* the owning
/// actor. When this drops to zero the object may be reclaimed.
pub ref_count: u32,
/// Foreign reference count — how many references exist in *other* actors.
/// Part of the ORCA protocol for cross-actor reference tracking.
pub foreign_count: u32,
/// When `true` the object is immortal (sticky) and must never be collected.
/// Used for global constants and pinned FFI buffers.
pub sticky: bool,
/// Size class bucket this object belongs to.
pub size_class: SizeClass,
/// GC tri-colour state.
pub gc_color: GcColor,
/// Runtime type tag — tells the GC how to scan this object's payload.
pub type_tag: TypeTag,
/// Padding to ensure `actor_id` (u64) is 8-byte aligned.
_pad: [u8; 4],
/// ID of the actor that owns this object.
pub actor_id: u64,
/// Total bytes allocated for this object (header + aligned payload).
pub size: usize,
/// Requested payload size in bytes (as passed to `alloc`).
pub payload_size: usize,
/// Intrusive next pointer for the live-object doubly-linked list.
/// This is internal to the allocator and not part of the public ORCA spec.
pub(crate) live_next: *mut OrcaHeader,
/// Intrusive previous pointer for the live-object doubly-linked list.
pub(crate) live_prev: *mut OrcaHeader,
}
impl OrcaHeader {
/// Create a *logically* initialised header on the caller's stack.
///
/// # Safety
/// The returned value must be copied into heap-backed storage (via
/// `ptr::write`) before it is observed by any heap/GC code.
pub(crate) fn new(
actor_id: u64,
type_tag: TypeTag,
total_size: usize,
payload_size: usize,
) -> Self {
let (size_class, _) = classify_total_size(total_size);
OrcaHeader {
ref_count: 1,
foreign_count: 0,
sticky: false,
size_class,
gc_color: GcColor::White,
type_tag,
_pad: [0; 4],
actor_id,
size: total_size,
payload_size,
live_next: std::ptr::null_mut(),
live_prev: std::ptr::null_mut(),
}
}
}
// ---------------------------------------------------------------------------
// ActorHeap
// ---------------------------------------------------------------------------
/// Per-actor heap allocator with ORCA-compatible object headers.
///
/// `ActorHeap` combines a fast bump allocator with size-class free lists.
/// All allocations are 8-byte aligned and carry an [`OrcaHeader`]. The
/// allocator maintains an intrusive doubly-linked list of *live* objects so
/// that the GC can walk all reachable objects in O(live) time.
///
/// # Thread safety
///
/// `ActorHeap` is **not** `Sync` — it is designed to be owned by a single
/// actor and accessed only while that actor is running. It **is** `Send`
/// so that an actor (and its heap) can be migrated between scheduler threads.
/// In practice the runtime is a single-threaded synchronous coordinator, so
/// all heap access happens on the one scheduler thread; header refcounts are
/// therefore plain integers, not atomics (see [`OrcaHeader`]).
#[derive(Debug)]
pub struct ActorHeap {
/// Owning actor ID (0 until `set_actor_id` is called).
actor_id: u64,
/// Base pointer of the *active* bump block (the one `current` bumps into).
base: *mut u8,
/// Bump pointer — next free byte in the active block.
current: *mut u8,
/// One-past-the-end pointer of the active block.
limit: *mut u8,
/// Total size of the active block (bytes).
total_size: usize,
/// Bytes committed by the bump pointer in the active block
/// (i.e. `current - base`).
used_bytes: usize,
/// Cumulative `used_bytes` of retired (exhausted) bump blocks.
prior_used: usize,
/// `(base, size)` of every retired bump block. Retired blocks are full:
/// their live objects stay put (objects never move) and their freed
/// objects sit in the shared size-class free lists. They are deallocated
/// on `reset`/`drop`.
retired_blocks: Vec<(*mut u8, usize)>,
/// Per-size-class intrusive free lists.
/// Each entry is either `null_mut()` or points to the payload of the
/// first free block in that class. The first 8 bytes of a free payload
/// store a `*mut u8` to the next free block. The `Huge` list doubles as
/// the large-object-space free list.
free_lists: [*mut u8; NUM_SIZE_CLASSES],
/// Payload pointers of every large-object-space block ever allocated by
/// this heap (live or sitting in the `Huge` free list). Each block is
/// individually malloc'd and must be individually deallocated on
/// `reset`/`drop`.
los_blocks: Vec<*mut u8>,
/// Head of the live-object doubly-linked list.
live_head: *mut OrcaHeader,
/// Tail of the live-object doubly-linked list.
live_tail: *mut OrcaHeader,
/// Number of objects currently in the live list.
live_count: usize,
/// Cumulative allocations (including reuses from free lists).
total_allocs: usize,
/// Cumulative frees.
total_frees: usize,
/// High-water mark of `used_bytes`.
peak_used: usize,
}
// ActorHeap can be sent between scheduler threads because it owns all of
// its memory and no other thread holds pointers into it.
unsafe impl Send for ActorHeap {}
/// Round `size` up to the next multiple of `ALIGN` (8).
#[inline(always)]
const fn align_up(size: usize) -> usize {
(size + ALIGN - 1) & !(ALIGN - 1)
}
impl ActorHeap {
/// Size of the ORCA header in bytes.
pub const HEADER_SIZE: usize = std::mem::size_of::<OrcaHeader>();
// ------------------------------------------------------------------
// Construction
// ------------------------------------------------------------------
/// Create a new per-actor heap with the given total backing size.
///
/// The backing memory is allocated with the global allocator and is
/// 8-byte aligned. The block is eagerly reserved but lazily committed
/// (the bump pointer touches pages on demand), and when it fills up the
/// heap grows by chaining another block — see [`ActorHeap::grow_bump_block`].
/// The `actor_id` defaults to `0`; the caller should
/// invoke [`ActorHeap::set_actor_id`] as soon as the real actor ID is
/// known.
///
/// # Panics
///
/// Panics if `total_size` is zero or the layout is invalid.
pub fn new(total_size: usize) -> Self {
assert!(total_size > 0, "ActorHeap size must be > 0");
// Try the thread-local heap pool before the global allocator.
let (base, actual_size) = HEAP_POOL
.with(|pool| pool.borrow_mut().acquire(total_size))
.unwrap_or_else(|| {
let layout = std::alloc::Layout::from_size_align(total_size, ALIGN)
.expect("invalid ActorHeap layout");
let base = unsafe { std::alloc::alloc(layout) };
if base.is_null() {
std::alloc::handle_alloc_error(layout);
}
(base, total_size)
});
ActorHeap {
actor_id: 0,
base,
current: base,
limit: unsafe { base.add(actual_size) },
total_size: actual_size,
used_bytes: 0,
prior_used: 0,
retired_blocks: Vec::new(),
free_lists: [std::ptr::null_mut(); NUM_SIZE_CLASSES],
los_blocks: Vec::new(),
live_head: std::ptr::null_mut(),
live_tail: std::ptr::null_mut(),
live_count: 0,
total_allocs: 0,
total_frees: 0,
peak_used: 0,
}
}
/// Set the owning actor ID.
///
/// All subsequently allocated objects will have this `actor_id` written
/// into their header. Existing objects are **not** updated.
pub fn set_actor_id(&mut self, id: u64) {
self.actor_id = id;
}
// ------------------------------------------------------------------
// Allocation
// ------------------------------------------------------------------
/// Allocate an object with the given payload size and type tag.
///
/// Returns a pointer to the **payload** (the writable region just past
/// the [`OrcaHeader`]). The header is automatically prepended and
/// initialised with:
///
/// * `ref_count = 1`
/// * `foreign_count = 0`
/// * `sticky = false`
/// * `gc_color = White`
/// * `actor_id` = the heap's current actor ID
/// * `size_class` computed from the total allocation size
///
/// # Algorithm
///
/// 1. Align `payload_size` to 8 bytes.
/// 2. Compute `total_size = HEADER_SIZE + aligned_payload`.
/// 3. Determine the size class.
/// 4. Check the corresponding free list — if a block is available, pop
/// it, rewrite the header fields, and return the payload pointer.
/// Large-object-space (`Huge`) blocks are only reused on an exact
/// size match, because each LOS block is individually deallocated
/// with its original layout on `reset`/`drop`.
/// 5. Otherwise fall back to bump allocation from the active block —
/// chaining a fresh block when the active one is exhausted — or to a
/// fresh LOS allocation when `total_size > LOS_THRESHOLD`. The bump
/// pointer advances by the uniform class block size (not the exact
/// total), so all blocks in a class are physically identical and
/// free-list reuse can never overrun a neighbour.
///
/// Returns `None` only if the global allocator fails (OS OOM); an
/// exhausted bump block triggers growth instead of failure.
pub fn alloc(&mut self, payload_size: usize, type_tag: TypeTag) -> Option<*mut u8> {
let aligned_payload = align_up(payload_size);
let total_size = Self::HEADER_SIZE + aligned_payload;
// `block_size` is the uniform physical size reserved for the class
// (the exact total for Huge/LOS blocks). The header still records
// the exact `total_size`, because the VM derives array / record /
// tuple element counts from it. Every reachable class block is
// >= HEADER_SIZE + ALIGN (the smallest is 64 bytes vs a 56-byte
// header), so even a zero-byte payload leaves room for `free`'s
// intrusive next-pointer.
let (size_class, block_size) = classify_total_size(total_size);
let sc_idx = size_class as usize;
// --- Fast path: try the free list for this size class ---
let reuse = unsafe {
if size_class == SizeClass::Huge {
// LOS blocks carry their original total size in the header;
// only an exact match keeps reset/drop deallocation correct.
self.take_los_block(total_size)
} else if !self.free_lists[sc_idx].is_null() {
// Pop the first block from the intrusive list.
let payload_ptr = self.free_lists[sc_idx];
// The first 8 bytes of the free payload hold the next pointer.
let next_free = *(payload_ptr as *mut *mut u8);
self.free_lists[sc_idx] = next_free;
Some(payload_ptr)
} else {
None
}
};
if let Some(payload_ptr) = reuse {
unsafe {
// Rewrite header (the old header values are stale).
let header_ptr = Self::header_of(payload_ptr);
// SAFETY: payload_ptr came from a previous alloc on this
// heap, so header_ptr points to a valid OrcaHeader inside
// our backing block or LOS region.
std::ptr::write(
header_ptr,
OrcaHeader::new(self.actor_id, type_tag, total_size, payload_size),
);
self.add_to_live_list(header_ptr);
}
self.live_count += 1;
self.total_allocs += 1;
return Some(payload_ptr);
}
// --- Large-object space: individually malloc'd block ---
if total_size > LOS_THRESHOLD {
return self.alloc_los(total_size, payload_size, type_tag);
}
// --- Slow path: bump allocation, chaining a new block on exhaustion ---
unsafe {
if self.current.add(block_size) > self.limit {
// The active block is full. Objects never move (raw payload
// pointers live in VM registers, foreign refs, and JIT code),
// so we chain a fresh block instead of reallocating.
self.grow_bump_block(block_size)?;
debug_assert!(self.current.add(block_size) <= self.limit);
}
let new_current = self.current.add(block_size);
let header_ptr = self.current as *mut OrcaHeader;
let payload_ptr = self.current.add(Self::HEADER_SIZE);
self.current = new_current;
self.used_bytes += block_size;
// Initialise the header in place.
std::ptr::write(
header_ptr,
OrcaHeader::new(self.actor_id, type_tag, total_size, payload_size),
);
self.add_to_live_list(header_ptr);
self.live_count += 1;
self.total_allocs += 1;
let committed = self.prior_used + self.used_bytes;
if committed > self.peak_used {
self.peak_used = committed;
}
Some(payload_ptr)
}
}
// ------------------------------------------------------------------
// Free
// ------------------------------------------------------------------
/// Free an object back to the free list for its size class.
///
/// `payload_ptr` must be a pointer previously returned by [`alloc`].
/// The object is removed from the live list and its payload memory is
/// repurposed as an intrusive linked-list node. Large-object-space
/// (`Huge`) blocks go onto the same intrusive list (they stay tracked in
/// `los_blocks` and are deallocated on `reset`/`drop`, not here).
///
/// # Safety
///
/// * `payload_ptr` must be valid and must have come from `alloc` on this
/// exact heap.
/// * No references to this object may remain — violating this is UB.
/// * This method must not be called twice on the same pointer (double-free).
pub unsafe fn free(&mut self, payload_ptr: *mut u8) {
// Recover the header.
let header_ptr = Self::header_of(payload_ptr);
// Remove from the live list.
self.remove_from_live_list(header_ptr);
self.live_count -= 1;
self.total_frees += 1;
// Read the size class so we know which free list to push to.
// Plain read: the single scheduler thread is the only mutator of
// any header (ActorHeap is !Sync).
let sc = (*header_ptr).size_class;
let sc_idx = sc as usize;
if sc_idx < NUM_SIZE_CLASSES {
// Intrusive free list: the first 8 bytes of the (now dead) payload
// store a pointer to the previous head of the free list.
//
// SAFETY: every block physically reserves at least ALIGN bytes of
// payload — alloc advances the bump pointer by the uniform class
// block size, and the smallest class block is 64 bytes against a
// 56-byte header — so there is always room for the next-pointer,
// even for zero-byte payloads.
*(payload_ptr as *mut *mut u8) = self.free_lists[sc_idx];
self.free_lists[sc_idx] = payload_ptr;
}
// If the size class is somehow out of range we simply leak the block.
// This should never happen because classify_total_size only returns
// valid discriminants.
}
// ------------------------------------------------------------------
// Header recovery
// ------------------------------------------------------------------
/// Recover the [`OrcaHeader`] pointer from a payload pointer.
///
/// # Safety
///
/// `payload_ptr` must point to the payload region of a valid allocation
/// on this heap (i.e. it must have been returned by `alloc`). The
/// header is located exactly `HEADER_SIZE` bytes before the payload
/// because of the `#[repr(C)]` layout.
pub unsafe fn header_of(payload_ptr: *mut u8) -> *mut OrcaHeader {
// Cast to *mut OrcaHeader and offset by -1. Because OrcaHeader is
// 56 bytes, this subtracts 56 bytes from the address, landing exactly
// on the header that was laid out immediately before the payload.
(payload_ptr as *mut OrcaHeader).offset(-1)
}
// ------------------------------------------------------------------
// Queries
// ------------------------------------------------------------------
/// Total bytes committed by the bump allocator across all chained blocks.
pub fn used(&self) -> usize {
self.prior_used + self.used_bytes
}
/// Remaining free space in the active bump block.
pub fn free_bytes(&self) -> usize {
self.total_size - self.used_bytes
}
/// Number of objects currently alive (allocated but not freed).
pub fn live_count(&self) -> usize {
self.live_count
}
/// Total number of objects sitting in free lists (available for reuse).
pub fn free_list_count(&self) -> usize {
let mut count = 0usize;
for sc_idx in 0..NUM_SIZE_CLASSES {
let mut cursor = self.free_lists[sc_idx];
while !cursor.is_null() {
count += 1;
// SAFETY: cursor is a payload pointer from a previous free()
// on this heap. The first 8 bytes hold the next pointer.
unsafe {
cursor = *(cursor as *mut *mut u8);
}
}
}
count
}
// ------------------------------------------------------------------
// Iteration
// ------------------------------------------------------------------
/// Iterate over all live objects.
///
/// Calls `callback` with `(header_ptr, payload_ptr, payload_size)` for
/// every object that is currently in the live list (i.e. allocated and
/// not yet freed). The order follows the allocation order because the
/// live list is append-only.
///
/// # Usage in GC mark phase
///
/// ```ignore
/// heap.iter_live_objects(|header, payload, size| {
/// unsafe {
/// (*header).gc_color = GcColor::Gray;
/// // enqueue payload for scanning ...
/// }
/// });
/// ```
pub fn iter_live_objects<F>(&self, mut callback: F)
where
F: FnMut(*mut OrcaHeader, *mut u8, usize),
{
let mut current = self.live_head;
while !current.is_null() {
unsafe {
// Payload starts one header stride past the header.
let payload_ptr = current.add(1) as *mut u8;
let payload_size = (*current).size - Self::HEADER_SIZE;
callback(current, payload_ptr, payload_size);
current = (*current).live_next;
}
}
}
// ------------------------------------------------------------------
// Reset
// ------------------------------------------------------------------
/// Reset the heap to a pristine state.
///
/// * The bump pointer returns to `base` of the active block.
/// * All retired (chained) blocks and large-object-space blocks are
/// deallocated.
/// * All free lists are discarded.
/// * The live-object list is cleared.
/// * Statistics are zeroed.
///
/// This is used when an actor is restarted by a supervisor. Any
/// outstanding pointers into this heap become dangling — the caller
/// must ensure none exist.
pub fn reset(&mut self) {
// Deallocate retired bump blocks and large-object-space blocks before
// discarding the free lists — the free lists point into those blocks.
self.release_retired_blocks();
self.release_los_blocks();
self.current = self.base;
self.used_bytes = 0;
self.prior_used = 0;
self.live_head = std::ptr::null_mut();
self.live_tail = std::ptr::null_mut();
self.live_count = 0;
self.free_lists = [std::ptr::null_mut(); NUM_SIZE_CLASSES];
self.total_allocs = 0;
self.total_frees = 0;
self.peak_used = 0;
}
// ==================================================================
// Internal helpers
// ==================================================================
/// Chain a fresh bump block onto the heap and make it the active block.
///
/// The exhausted block is retired — kept mapped, not copied — because its
/// live objects must never move (raw payload pointers are held in VM
/// registers, other actors' foreign refs, and JIT code). Retired blocks
/// are deallocated on `reset`/`drop`.
///
/// The new block is the same size as the exhausted one, or `min_capacity`
/// when a single allocation needs more. Equal-size chaining (rather than
/// doubling) keeps per-actor memory growth linear and predictable: an
/// actor's footprint stays proportional to the data it actually holds.
///
/// Returns `None` only when the global allocator fails.
fn grow_bump_block(&mut self, min_capacity: usize) -> Option<()> {
let new_size = self.total_size.max(min_capacity);
let layout = std::alloc::Layout::from_size_align(new_size, ALIGN).ok()?;
// SAFETY: layout has non-zero size (`total_size` > 0) and is valid.
let base = unsafe { std::alloc::alloc(layout) };
if base.is_null() {
// Report OS OOM as exhaustion, matching alloc's `None` contract.
return None;
}
// Retire the exhausted block; its contents stay exactly where they are.
self.retired_blocks.push((self.base, self.total_size));
self.prior_used += self.used_bytes;
self.base = base;
self.current = base;
self.limit = unsafe { base.add(new_size) };
self.total_size = new_size;
self.used_bytes = 0;
Some(())
}
/// Deallocate every retired (exhausted) bump block.
///
/// Called from `reset` and `drop`. Any live objects in these blocks are
/// abandoned — the caller must ensure no outstanding pointers exist.
fn release_retired_blocks(&mut self) {
for &(base, size) in &self.retired_blocks {
// Return to the thread-local pool instead of deallocating.
HEAP_POOL.with(|pool| {
pool.borrow_mut().release(base, size);
});
}
self.retired_blocks.clear();
}
/// Allocate a large-object-space block with the global allocator.
///
/// The block is tracked in `los_blocks` so it can be individually
/// deallocated on `reset`/`drop`. `total_size` must already include the
/// header and be 8-byte aligned.
fn alloc_los(
&mut self,
total_size: usize,
payload_size: usize,
type_tag: TypeTag,
) -> Option<*mut u8> {
let layout = std::alloc::Layout::from_size_align(total_size, ALIGN).ok()?;
// SAFETY: layout is non-zero (total_size >= HEADER_SIZE) and valid.
let base = unsafe { std::alloc::alloc(layout) };
if base.is_null() {
// Report OOM as exhaustion, matching alloc's `None` contract.
return None;
}
let header_ptr = base as *mut OrcaHeader;
// SAFETY: `base` points to a fresh block of at least HEADER_SIZE +
// aligned payload bytes, so the payload region is in bounds.
let payload_ptr = unsafe { base.add(Self::HEADER_SIZE) };
// SAFETY: header_ptr points to writable memory we just allocated.
unsafe {
std::ptr::write(
header_ptr,
OrcaHeader::new(self.actor_id, type_tag, total_size, payload_size),
);
self.add_to_live_list(header_ptr);
}
self.los_blocks.push(payload_ptr);
self.live_count += 1;
self.total_allocs += 1;
Some(payload_ptr)
}
/// Pop a large-object-space block whose total size exactly matches
/// `total_size` from the `Huge` free list.
///
/// Exact-size matching is required because each LOS block is deallocated
/// with its original layout; reusing a larger block for a smaller request
/// would lose the true allocation size.
///
/// # Safety
/// The `Huge` free list must contain only payload pointers from previous
/// `free` calls on this heap.
unsafe fn take_los_block(&mut self, total_size: usize) -> Option<*mut u8> {
let huge_idx = SizeClass::Huge as usize;
let mut prev: *mut u8 = std::ptr::null_mut();
let mut cursor = self.free_lists[huge_idx];
while !cursor.is_null() {
// SAFETY: cursor is a payload pointer from a previous free() on
// this heap. The first 8 bytes hold the next pointer and the
// header one stride back holds the block's original total size.
let next = *(cursor as *mut *mut u8);
let header = Self::header_of(cursor);
if (*header).size == total_size {
if prev.is_null() {
self.free_lists[huge_idx] = next;
} else {
*(prev as *mut *mut u8) = next;
}
return Some(cursor);
}
prev = cursor;
cursor = next;
}
None
}
/// Deallocate every tracked large-object-space block.
///
/// Called from `reset` and `drop`. The `Huge` free list must already
/// have been discarded (or be discarded immediately after) so no stale
/// pointers into the released blocks survive.
fn release_los_blocks(&mut self) {
for &payload_ptr in &self.los_blocks {
// SAFETY: every pointer in `los_blocks` was returned by
// `alloc_los` on this heap and is deallocated exactly once here;
// the header one stride back records the original total size
// used for the matching `Layout`.
unsafe {
let header_ptr = Self::header_of(payload_ptr);
let layout = std::alloc::Layout::from_size_align((*header_ptr).size, ALIGN)
.expect("invalid LOS layout");
std::alloc::dealloc(header_ptr as *mut u8, layout);
}
}
self.los_blocks.clear();
}
/// Append `header_ptr` to the tail of the live-object doubly-linked list.
///
/// # Safety
/// `header_ptr` must point to a valid, writable `OrcaHeader` inside this
/// heap's backing block. This function is called only from `alloc`.
unsafe fn add_to_live_list(&mut self, header_ptr: *mut OrcaHeader) {
(*header_ptr).live_next = std::ptr::null_mut();
(*header_ptr).live_prev = self.live_tail;
if self.live_tail.is_null() {
// First object.
self.live_head = header_ptr;
} else {
(*self.live_tail).live_next = header_ptr;
}
self.live_tail = header_ptr;
}
/// Remove `header_ptr` from the live-object doubly-linked list.
///
/// # Safety
/// `header_ptr` must be a current member of the live list.
unsafe fn remove_from_live_list(&mut self, header_ptr: *mut OrcaHeader) {
let prev = (*header_ptr).live_prev;
let next = (*header_ptr).live_next;
if prev.is_null() {
self.live_head = next;
} else {
(*prev).live_next = next;
}
if next.is_null() {
self.live_tail = prev;
} else {
(*next).live_prev = prev;
}
}
}
// ---------------------------------------------------------------------------
// OrcaHeap trait implementation
// ---------------------------------------------------------------------------
use super::gc::OrcaHeap;
impl OrcaHeap for ActorHeap {
/// Allocate payload bytes with the Raw type tag.
///
/// Delegates to [`ActorHeap::alloc`] using [`TypeTag::Raw`] as the
/// default type tag. The ORCA GC (in `gc.rs`) calls this when it needs
/// to allocate an object whose type will be determined later.
fn alloc_payload(&mut self, payload_size: usize) -> Option<*mut u8> {
self.alloc(payload_size, TypeTag::Raw)
}
/// Free a payload previously returned by [`alloc_payload`].
///
/// Delegates directly to [`ActorHeap::free`].
///
/// # Safety
/// `payload_ptr` must be a live pointer returned by `alloc_payload` on
/// this exact heap.
unsafe fn free_payload(&mut self, payload_ptr: *mut u8) {
self.free(payload_ptr);
}
/// Recover the [`OrcaHeader`] pointer from a payload pointer.
///
/// # Safety
/// `payload_ptr` must be a valid payload pointer from this heap.
unsafe fn header_ptr(&self, payload_ptr: *mut u8) -> *mut OrcaHeader {
ActorHeap::header_of(payload_ptr)
}
}
// ---------------------------------------------------------------------------
// HeapPool — recycled bump-allocator blocks across actor generations
// ---------------------------------------------------------------------------
/// A pool of deallocated bump-allocator blocks that can be reused for new
/// actors. When an actor exits and its heap is below the pooling threshold,
/// the blocks are returned here instead of being freed. The next actor
/// spawn draws from the pool before calling the global allocator.
///
/// This is safe because:
/// - Blocks are only returned to the pool after the owning actor has exited,
/// all live objects have been reclaimed, and no foreign references remain.
/// - The runtime is single-threaded per shard, so no synchronization is needed.
pub struct HeapPool {
/// Recycled blocks: `(base_ptr, size_bytes)`.
blocks: Vec<(*mut u8, usize)>,
/// Maximum number of blocks to hold. When exceeded, the oldest block is
/// deallocated.
max_blocks: usize,
/// Only pool blocks whose size is ≤ this threshold. Oversized heaps
/// (actors that grew via chaining) are deallocated directly.
size_threshold: usize,
}
impl HeapPool {
/// Create a new pool.
///
/// `max_blocks`: maximum number of recycled blocks to retain.
/// `size_threshold`: only blocks ≤ this size (bytes) are pooled.
pub fn new(max_blocks: usize, size_threshold: usize) -> Self {
HeapPool {
blocks: Vec::new(),
max_blocks,
size_threshold,
}
}
/// Try to acquire a recycled block of at least `min_size` bytes.
/// Returns `None` when the pool is empty or no block is large enough.
pub fn acquire(&mut self, min_size: usize) -> Option<(*mut u8, usize)> {
// Best-fit: find the smallest block that satisfies the request.
let mut best_idx = None;
let mut best_size = usize::MAX;
for (i, &(_base, size)) in self.blocks.iter().enumerate() {
if size >= min_size && size < best_size {
best_idx = Some(i);
best_size = size;
}
}
best_idx.map(|i| self.blocks.swap_remove(i))
}
/// Return a block to the pool for reuse.
///
/// The block will only be retained if its size is ≤ `size_threshold`.
/// Blocks above the threshold, and excess blocks when `max_blocks` is
/// exceeded, are deallocated immediately.
fn release(&mut self, base: *mut u8, size: usize) {
if size > self.size_threshold {
// Oversized block: deallocate immediately.
let layout = std::alloc::Layout::from_size_align(size, ALIGN)
.expect("invalid pooled block layout");
unsafe {
std::alloc::dealloc(base, layout);
}
return;
}
self.blocks.push((base, size));
// Evict oldest block if over limit.
while self.blocks.len() > self.max_blocks {
let (base, size) = self.blocks.remove(0);
let layout = std::alloc::Layout::from_size_align(size, ALIGN)
.expect("invalid pooled block layout");
unsafe {
std::alloc::dealloc(base, layout);
}
}
}
/// Number of blocks currently in the pool.
pub fn len(&self) -> usize {
self.blocks.len()
}
/// Whether the pool is empty.
pub fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
}
impl Drop for HeapPool {
fn drop(&mut self) {
for (base, size) in self.blocks.drain(..) {
let layout = std::alloc::Layout::from_size_align(size, ALIGN)
.expect("invalid pooled block layout");
unsafe {
std::alloc::dealloc(base, layout);
}
}