Skip to main content

kevy_alloc/
heap.rs

1//! The per-shard heap.
2//!
3//! # Why there is no thread-local cache in front of this
4//!
5//! tcmalloc and mimalloc put a thread cache ahead of a shared central
6//! heap because they cannot know how threads relate to memory, and
7//! torajs-mmalloc's finding doc records what happens without one: its
8//! first cutover cost 10–30 ns per allocation and reversed alloc-heavy
9//! benchmarks by up to 4×, until a TLAB went in front.
10//!
11//! kevy pins a shard per core and routes every key to its owner, so the
12//! heap **is** the thread-local structure. The fast path pops from the
13//! current span's free list with no atomics — which is what a thread
14//! cache exists to achieve. Adding one here would put a cache in front
15//! of a cache. This is the divergence from the references that ROADMAP
16//! rule ② asks to be stated rather than assumed.
17//!
18//! Cross-shard frees are real (values travel on the shared read lane),
19//! and they are handled by [`segment::push_foreign`] — push-only, so
20//! there is no ABA hazard to inherit.
21
22use core::ptr::NonNull;
23
24use crate::class::{self, NCLASSES};
25use crate::os;
26use crate::outbound::Outbound;
27use crate::partials::PartialRing;
28use crate::segment::{
29    self, FIRST_DATA_SPAN, NO_CLASS, SEGMENT_BYTES, SPANS_PER_SEGMENT, Segment,
30};
31
32/// Spans one class may hold at once, per heap — a runaway guard, not a
33/// policy. At 64 KiB a span, this bounds one class at roughly 4 GiB per
34/// shard, which no correct program reaches by accident.
35///
36/// torajs-mmalloc shipped without any cap and paid for it (`c2970b6d`):
37/// a legal program exhausted a class, the allocator returned `None`, and
38/// the null propagated into a write — a SIGSEGV on correct code. What
39/// actually protects a Rust program is that a null from `alloc` becomes
40/// `handle_alloc_error` and a clean abort; the cap only makes runaway
41/// growth arrive there sooner.
42///
43/// **The inherited value was 64 spans — 4 MiB a class — and it was wrong
44/// by three orders of magnitude for this engine.** The standard library
45/// found it on the first run that put real work through the allocator: a
46/// test holding tens of thousands of buffers of one size hit the ceiling
47/// and aborted with "memory allocation of 6152 bytes failed" while the
48/// machine had gigabytes free. A number that is right for a JavaScript
49/// runtime's object churn is not right for a data engine, and copying it
50/// across was the mistake.
51///
52/// [`Heap::with_class_cap`] takes a tighter bound where one is wanted —
53/// which is how the exhaustion path stays testable now that the default
54/// is out of reach.
55///
56/// **The same lesson, second verse:** the raise above was silently
57/// pinned by its own `u16` — 65,535 spans × 64 KiB is a hidden 4 GiB
58/// ceiling *per class*, and the first hour-long soak found it: a
59/// 3-byte-value storm filled the 16 B class and the process aborted
60/// with "memory allocation of 3 bytes failed" on a box with 48 GiB
61/// free. The counter is now `u32` and the guard sits at 1 TiB per
62/// class — memory governance belongs to maxmemory and the tier
63/// budget, never to an invisible allocator constant.
64pub const PER_CLASS_CAP: u32 = 16_777_216;
65
66/// Empty spans a heap keeps mapped-but-discarded before releasing the
67/// whole segment. Decay-style hysteresis, after jemalloc: releasing
68/// eagerly turns a churny workload into an mmap/munmap storm.
69pub const EMPTY_SPAN_HYSTERESIS: u16 = 4;
70
71
72/// One shard's heap. Not `Sync`: exactly one thread owns it, which is
73/// what removes the atomics from the fast path.
74pub struct Heap {
75    id: usize,
76    pub(crate) segments: *mut Segment,
77    /// Current span per class, as (segment, span index).
78    pub(crate) partial: [Option<(NonNull<Segment>, u8)>; NCLASSES],
79    pub(crate) spans_in_class: [u32; NCLASSES],
80    pub(crate) live_bytes: u64,
81    pub(crate) rounding_bytes: u64,
82    /// Foreign frees awaiting batched shipment home. The free fast path
83    /// only ever appends here — the cross-core traffic all lives in the
84    /// flush. See `outbound.rs` for why this shape and not tcache-style
85    /// local reuse.
86    pub(crate) outbound: Outbound,
87    /// Per-class ring of spans believed to have room — pushed when a
88    /// free makes a full span partial, popped by the slow path before
89    /// it falls back to scanning.
90    ///
91    /// The legacy profile forced this (finding
92    /// the mmap-lock finding's follow-up): with the
93    /// 16–32 KiB classes a span holds 2–8 slots, so churn exhausts one
94    /// every few allocations, and the slow path's two O(segments)
95    /// scans put `Heap::alloc` at 6 % of server self time. This is
96    /// mimalloc's page-queue-per-class, sized as a ring because entries
97    /// may go stale (a span can be reassigned after its entry is
98    /// pushed) — the pop validates and simply discards liars.
99    partials: [PartialRing; NCLASSES],
100    /// Per-class claimed bitmap word (the far-line amortizer): up to 64
101    /// slots of the current span's lowest holed word, handed out and
102    /// locally recycled without touching the segment header. One header
103    /// round-trip per 64 slots instead of per slot — the collection-write
104    /// residual this shape exists for. `claimed & !taken` are the bits
105    /// owed back to the span on retire.
106    claims: [Option<Claim>; NCLASSES],
107    class_cap: u32,
108}
109
110impl Heap {
111    /// A heap owning nothing. `id` identifies the shard in stats and in
112    /// segment headers.
113    #[must_use]
114    pub const fn new(id: usize) -> Self {
115        Self::with_class_cap(id, PER_CLASS_CAP)
116    }
117
118    /// A heap with a tighter per-class ceiling than [`PER_CLASS_CAP`].
119    ///
120    /// The default is a runaway guard set beyond any real workload,
121    /// which leaves the refusal path unreachable in a test. This makes
122    /// it reachable without pretending the default is smaller than it is.
123    #[must_use]
124    pub const fn with_class_cap(id: usize, class_cap: u32) -> Self {
125        Self {
126            id,
127            segments: core::ptr::null_mut(),
128            partial: [None; NCLASSES],
129            spans_in_class: [0; NCLASSES],
130            live_bytes: 0,
131            rounding_bytes: 0,
132            outbound: Outbound::new(),
133            partials: [PartialRing::EMPTY; NCLASSES],
134            claims: [None; NCLASSES],
135            class_cap,
136        }
137    }
138
139    /// Adopt this heap's address as its identity, once.
140    ///
141    /// Segments record their owner so a free arriving on the wrong
142    /// thread can be routed home. The address of the heap itself is a
143    /// ready-made unique identifier — no counter, no registry, and it
144    /// cannot collide while the heap is alive. `0` means "not yet set",
145    /// which is why [`Heap::new`] can stay `const`.
146    pub fn ensure_identity(&mut self) {
147        if self.id == 0 {
148            self.id = core::ptr::from_mut(self) as usize;
149        }
150    }
151
152    /// Allocate `size` bytes aligned to `align`, or `None` if the OS or
153    /// a class cap says no.
154    ///
155    /// Alignment up to [`class::MAX_NATIVE_ALIGN`] is served by choosing
156    /// a suitable class. Stricter requests fall to the direct-mapping
157    /// path, which returns page-aligned memory; anything beyond a page
158    /// belongs to the `GlobalAlloc` shim's over-aligned path.
159    pub fn alloc(&mut self, size: usize, align: usize) -> Option<NonNull<u8>> {
160        match class::index_of(size, align) {
161            Some(c) => self.alloc_small(c, size),
162            None => self.alloc_large(size, align),
163        }
164    }
165
166    /// Grow or shrink in place when the block's size class does not
167    /// change, reporting whether it worked.
168    ///
169    /// This is the capability a general-purpose allocator gets from its
170    /// chunk headers: glibc can often extend a block where it lies
171    /// instead of moving it. Without it, `GlobalAlloc`'s default
172    /// `realloc` allocates, copies and frees on every growth — and a
173    /// profile of pub/sub showed exactly that, with `libc realloc`
174    /// visible and cheap on the system side and nothing corresponding
175    /// on ours.
176    ///
177    /// Refuses when the block belongs to another thread. Adjusting the
178    /// owner's counters from here is precisely what this design does not
179    /// do, and the caller falls back to allocate-copy-free, which routes
180    /// the release home correctly.
181    ///
182    /// # Safety
183    /// `ptr` must be a live allocation from this allocator made with
184    /// `old_size` and `align`.
185    pub unsafe fn try_resize_in_place(
186        &mut self,
187        ptr: NonNull<u8>,
188        old_size: usize,
189        new_size: usize,
190        align: usize,
191    ) -> bool {
192        let (Some(a), Some(b)) = (class::index_of(old_size, align), class::index_of(new_size, align))
193        else {
194            return false;
195        };
196        if a != b {
197            return false;
198        }
199        // SAFETY: a small allocation always lies inside a segment.
200        let seg = unsafe { segment::segment_of(ptr) };
201        // SAFETY: the mask lands on a live header for our own pointers.
202        if unsafe { seg.as_ref() }.owner != self.id {
203            return false;
204        }
205        let slot = class::size_of(a) as u64;
206        self.live_bytes = self.live_bytes - old_size as u64 + new_size as u64;
207        self.rounding_bytes = self.rounding_bytes - (slot - old_size as u64)
208            + (slot - new_size as u64);
209        true
210    }
211
212    /// Return an allocation. `size` must be the one it was made with —
213    /// the sized-dealloc contract is what lets us store no headers.
214    ///
215    /// # Safety
216    /// `ptr` must come from [`Self::alloc`] on this heap with this
217    /// `size`, and must not be used afterwards.
218    pub unsafe fn dealloc(&mut self, ptr: NonNull<u8>, size: usize, align: usize) {
219        match class::index_of(size, align) {
220            // SAFETY: delegated to the caller's contract.
221            Some(c) => unsafe { self.dealloc_small(ptr, c, size) },
222            None => unsafe { self.dealloc_large(ptr, size) },
223        }
224    }
225
226    /// Every allocation goes through the bitmap, lowest-first — there
227    /// is deliberately no free-slot cache in front of it.
228    ///
229    /// One existed. Its premise (keeping the hot free list in
230    /// heap-local memory) died with the locality hypothesis, it never
231    /// won a measurable point of throughput anywhere (0.826 → 0.844,
232    /// inside the band), and the M3 re-measurement convicted it of
233    /// costing 137 MB of the memory result: LIFO reuse hands back the
234    /// most recently freed slot regardless of position, which undoes
235    /// the lowest-first densification that page-granular reclaim feeds
236    /// on — resident went 1.98× → 2.38× with the cache in place. The
237    /// allocator's reason to exist outranks a cache that pays nothing.
238    fn alloc_small(&mut self, c: usize, size: usize) -> Option<NonNull<u8>> {
239        let slot = self.pop_slot(c).or_else(|| self.slow_path(c))?;
240        self.live_bytes += size as u64;
241        self.rounding_bytes += (class::size_of(c) - size) as u64;
242        Some(slot)
243    }
244
245    /// The current span had nothing. Look wider before asking the OS.
246    ///
247    /// The order matters, and one step here was missing at first: slots
248    /// freed into a span that is *not* the current one land on that
249    /// span's own free list, so without [`Self::adopt_partial`] those
250    /// spans are never revisited. Allocation would keep claiming fresh
251    /// spans past perfectly reusable ones until `PER_CLASS_CAP` refused
252    /// — looking exactly like a leak while every byte was accounted for.
253    fn slow_path(&mut self, c: usize) -> Option<NonNull<u8>> {
254        // O(1) first: spans the free path registered as having room.
255        // Entries can be stale — validate, discard liars.
256        while let Some((seg, ix)) = self.partials[c].pop() {
257            // SAFETY: rings only hold segments from this heap's list,
258            // which live as long as the heap.
259            let m = unsafe { &(*seg).spans[ix] };
260            if m.class as usize == c && u32::from(m.live) < m.capacity() {
261                // SAFETY: non-null by construction of the ring.
262                self.partial[c] = Some((unsafe { NonNull::new_unchecked(seg) }, ix as u8));
263                if let Some(p) = self.pop_slot(c) {
264                    return Some(p);
265                }
266            }
267        }
268        self.drain_foreign();
269        if self.adopt_partial(c)
270            && let Some(p) = self.pop_slot(c)
271        {
272            return Some(p);
273        }
274        self.claim_span(c)?;
275        self.pop_slot(c)
276    }
277
278    /// Make some span of class `c` that still has room the current one.
279    fn adopt_partial(&mut self, c: usize) -> bool {
280        let mut seg = self.segments;
281        while !seg.is_null() {
282            // SAFETY: the list holds live segment headers only.
283            let s = unsafe { &*seg };
284            for ix in FIRST_DATA_SPAN..SPANS_PER_SEGMENT {
285                let m = &s.spans[ix];
286                if m.class as usize == c && u32::from(m.live) < m.capacity() {
287                    // SAFETY: `seg` is non-null in this branch.
288                    self.partial[c] = Some((unsafe { NonNull::new_unchecked(seg) }, ix as u8));
289                    return true;
290                }
291            }
292            seg = s.next;
293        }
294        false
295    }
296
297    /// Take the lowest free slot from the class's current span, without
298    /// falling back. Lowest-first is the densification property: live
299    /// slots pack toward a span's low pages, so churn migrates free
300    /// space upward into whole pages the reclaim sweep can return.
301    ///
302    /// The handout comes from the class's claimed word; only when it
303    /// runs dry does the span header get touched again (one claim per
304    /// 64 slots — the far-line amortizer).
305    fn pop_slot(&mut self, c: usize) -> Option<NonNull<u8>> {
306        if let Some(p) = self.pop_claimed(c) {
307            return Some(p);
308        }
309        self.refill_claim(c)?;
310        self.pop_claimed(c)
311    }
312
313    /// Assign a span to class `c` and make it current, mapping a new
314    /// segment if no free span exists. `None` means the cap or the OS
315    /// refused.
316    fn claim_span(&mut self, c: usize) -> Option<()> {
317        if self.spans_in_class[c] >= self.class_cap {
318            return None;
319        }
320        let (seg, ix) = self.find_free_span().or_else(|| {
321            self.map_segment()?;
322            self.find_free_span()
323        })?;
324        // SAFETY: `find_free_span` returns a span of a live segment.
325        let meta = unsafe { &mut (*seg.as_ptr()).spans[ix] };
326        meta.reset(c as u8);
327        self.spans_in_class[c] += 1;
328        self.partial[c] = Some((seg, ix as u8));
329        Some(())
330    }
331
332    /// First span not assigned to a class, across this heap's segments.
333    fn find_free_span(&self) -> Option<(NonNull<Segment>, usize)> {
334        let mut seg = self.segments;
335        while !seg.is_null() {
336            // SAFETY: the list holds live segment headers only.
337            let s = unsafe { &*seg };
338            for ix in FIRST_DATA_SPAN..SPANS_PER_SEGMENT {
339                if s.spans[ix].class == NO_CLASS {
340                    // SAFETY: `seg` is non-null in this branch.
341                    return Some((unsafe { NonNull::new_unchecked(seg) }, ix));
342                }
343            }
344            seg = s.next;
345        }
346        None
347    }
348
349    /// Map a new segment and link it in. `None` when the OS refuses.
350    fn map_segment(&mut self) -> Option<()> {
351        let base = os::map_aligned(SEGMENT_BYTES, SEGMENT_BYTES)?;
352        // SAFETY: a fresh exclusive mapping of exactly one segment.
353        let seg = unsafe { Segment::init(base, self.id) };
354        // SAFETY: just initialised and owned solely by this heap.
355        unsafe { (*seg.as_ptr()).next = self.segments };
356        self.segments = seg.as_ptr();
357        Some(())
358    }
359
360    fn alloc_large(&mut self, size: usize, align: usize) -> Option<NonNull<u8>> {
361        crate::large::alloc(size, align)
362    }
363
364    /// # Safety
365    /// See [`Self::dealloc`].
366    unsafe fn dealloc_large(&mut self, ptr: NonNull<u8>, size: usize) {
367        // SAFETY: delegated to the caller's contract.
368        unsafe { crate::large::dealloc(ptr, size) };
369    }
370}
371
372
373impl Drop for Heap {
374    fn drop(&mut self) {
375        // Claims hold no memory of their own — the segments they point
376        // into are unmapped below — but retiring them keeps the
377        // debug-assert bookkeeping (live counts) honest for any
378        // instrumented teardown that walks spans first.
379        self.flush_claims();
380        // The retention pool is process-wide and bounded, so a heap's
381        // death owes it nothing — but the fuzzer's tight RSS limit
382        // watches every iteration, and draining here keeps single-heap
383        // lifecycles (tests, fuzz) at zero retained bytes. Its per-heap
384        // ancestor forgot the equivalent and leaked a mapping per heap.
385        crate::large::pool_drain();
386        let mut seg = self.segments;
387        while !seg.is_null() {
388            // SAFETY: live header from our own list; read `next` before
389            // the mapping goes away.
390            let next = unsafe { (*seg).next };
391            // SAFETY: this heap mapped it and is the only owner.
392            unsafe {
393                os::unmap(NonNull::new_unchecked(seg.cast::<u8>()), SEGMENT_BYTES);
394            }
395            seg = next;
396        }
397    }
398}
399
400#[path = "heap_claims.rs"]
401mod heap_claims;
402#[path = "heap_free.rs"]
403mod heap_free;
404pub(crate) use heap_claims::Claim;