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