From 5c14d8a97e4da4d0a682f7b08329b762b4ecea8e Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:47:06 -0500 Subject: [PATCH] fix(heap): size-class blocks come from slabs of one class that go back to the bins whole when empty, where each small block took a header among large blocks and its class kept it for good, so long sessions held a million free extents and a heap drain scattered them --- crates/stela-boot-core/src/heap.rs | 408 +++++++++++++++--- .../stela-boot-core/src/heap/failure/tests.rs | 11 +- crates/stela-boot-core/src/heap/replay.rs | 393 +++++++++++++++++ crates/stela-boot-core/src/heap/tests.rs | 88 +++- crates/stela-boot/src/engine/run.rs | 11 +- 5 files changed, 826 insertions(+), 85 deletions(-) create mode 100644 crates/stela-boot-core/src/heap/replay.rs diff --git a/crates/stela-boot-core/src/heap.rs b/crates/stela-boot-core/src/heap.rs index 3a8c645649..c54a0686ee 100644 --- a/crates/stela-boot-core/src/heap.rs +++ b/crates/stela-boot-core/src/heap.rs @@ -6,10 +6,13 @@ //! //! The system engine allocates and frees small blocks constantly. Blocks of up //! to 4 KiB with at most 16-byte alignment are therefore rounded up to a -//! power-of-two size class and, once freed, kept on that class's LIFO list -//! for the next allocation of the class instead of returning to the bins. -//! When the bins cannot serve a request, the class lists return to them, so -//! blocks of one size never starve a request of another. +//! power-of-two size class and served from slabs: runs of 16 to 64 KiB, each +//! carved from the bins at an address aligned to its size and cut into +//! blocks of one class, with no header per block. A freed block goes back to +//! its slab, found from its address; a slab whose blocks are all free goes +//! back to the bins whole, but for one kept per class. Small blocks therefore +//! take no headers, never lie scattered among large ones, and the memory a +//! class no longer uses returns to the bins as extents of tens of KiB. //! //! Every PE on a core of its own allocates at once, so each core the engine //! runs on keeps a small cache of free blocks per class ([`Heap::tag_cpu`]), @@ -19,10 +22,9 @@ //! counts packed beside other cores' would move their line between the //! cores on every allocation and free. //! -//! Small blocks that live for different lengths of time leave holes, and a -//! long run can hold a fifth of the heap free with no extent of a few MiB, so -//! the engine keeps the heap's end out of the main bins ([`Heap::reserve_tail`]): -//! a large request the main bins cannot serve takes it. Linux keeps +//! Blocks that live for different lengths of time leave holes, so the engine +//! keeps the heap's end out of the main bins ([`Heap::reserve_tail`]): a +//! large request the main bins cannot serve takes it. Linux keeps //! `ZONE_MOVABLE` and CMA apart from unmovable allocations for the same reason. use core::{ alloc::{GlobalAlloc, Layout}, @@ -208,6 +210,47 @@ struct Small { const SMALLEST: usize = 16; const CLASSES: usize = 9; const SMALL_ALIGNMENT: usize = 16; + +/// A slab's bookkeeping, after the boundary tag at its aligned start; its +/// blocks follow from [`SLAB_FIRST`]. Read and written with the lock held. +#[repr(C)] +struct Slab { + /// Its neighbours in its class's list of slabs with free blocks. + next: *mut Slab, + previous: *mut Slab, + /// Its freed blocks. + free: *mut Small, + /// Blocks out of the slab: live, or in a core's cache. + used: u32, + /// Blocks from this index on were never handed out. + fresh: u32, + capacity: u32, +} +/// Where a slab's first block lies from its aligned start: past its +/// boundary tag and its [`Slab`]. +const SLAB_FIRST: usize = 64; +const _: () = assert!(HEADER_BYTES + core::mem::size_of::() <= SLAB_FIRST); +/// Slabs are at least this large, and at most [`SLAB_LARGEST`]: a class's +/// slab holds 64 of its blocks within those bounds. +const SLAB_SMALLEST: usize = 16 << 10; +const SLAB_LARGEST: usize = 64 << 10; + +/// The bytes of a slab of `class`, a power of two its slabs are aligned to. +const fn slab_bytes(class: usize) -> usize { + let bytes = (SMALLEST << class) * 64; + if bytes < SLAB_SMALLEST { + SLAB_SMALLEST + } else if bytes > SLAB_LARGEST { + SLAB_LARGEST + } else { + bytes + } +} + +/// The slab of `block`, a block of `class`. +fn slab_of(block: *mut u8, class: usize) -> *mut Slab { + ((block as usize & !(slab_bytes(class) - 1)) + HEADER_BYTES) as *mut Slab +} /// Cores with a cache of their own; later ones take the lock every time. const CPUS: usize = 64; /// Free blocks a core keeps per class, and moves to or from the class list @@ -360,7 +403,13 @@ struct State { pools: [Bins; 2], /// Free blocks in the bins. extents: usize, - small: [*mut Small; CLASSES], + /// Each class's slabs with free blocks, the one taken from first at the + /// head, and the empty slab it keeps. + partial: [*mut Slab; CLASSES], + spare: [*mut Slab; CLASSES], + /// Slabs carved, and the bytes of their blocks not out of them. + slabs: usize, + slab_free: usize, ready: bool, total: usize, /// Bytes allocated and not freed, size-class blocks by their class. @@ -470,6 +519,45 @@ impl State { } } + /// Link `slab` of `class` at the head of its class's list: the slab + /// taken from next. + /// + /// # Safety + /// The lock is held and `slab` is a slab of `class` in no list. + unsafe fn list_slab(&mut self, class: usize, slab: *mut Slab) { + let head = self.partial[class]; + // SAFETY: the caller's slab; `head`, when not null, is a listed one. + unsafe { + (*slab).next = head; + (*slab).previous = ptr::null_mut(); + if !head.is_null() { + (*head).previous = slab; + } + } + self.partial[class] = slab; + } + + /// Unlink `slab` of `class` from its class's list. + /// + /// # Safety + /// The lock is held and `slab` is in the list of `class`. + unsafe fn unlist_slab(&mut self, class: usize, slab: *mut Slab) { + // SAFETY: the caller's listed slab and its listed neighbours. + unsafe { + let (next, previous) = ((*slab).next, (*slab).previous); + if !next.is_null() { + (*next).previous = previous; + } + if previous.is_null() { + self.partial[class] = next; + } else { + (*previous).next = next; + } + (*slab).next = ptr::null_mut(); + (*slab).previous = ptr::null_mut(); + } + } + fn count_large(&mut self, bytes: usize, allocated: bool) { let (count, total) = &mut self.large[large_bucket(bytes)]; if allocated { @@ -493,6 +581,11 @@ pub struct Usage { pub largest: usize, /// Free blocks in the bins. pub extents: usize, + /// Size-class slabs carved, and the bytes of their blocks that are + /// free in them: what the classes keep beside their live blocks, short + /// of the cores' caches. + pub slabs: usize, + pub slab_free: usize, /// Allocations the bins served. pub carves: u64, /// Live allocations the bins served, as count and bytes by power @@ -577,7 +670,10 @@ impl Heap { floor: 0, pools: [Bins::EMPTY; 2], extents: 0, - small: [ptr::null_mut(); CLASSES], + partial: [ptr::null_mut(); CLASSES], + spare: [ptr::null_mut(); CLASSES], + slabs: 0, + slab_free: 0, ready: false, total: 0, live: 0, @@ -856,8 +952,8 @@ impl Heap { /// Whether more than three quarters of the heap is allocated, as the /// lock and each core's cache last left it, or so nearly all of the main /// bins' bytes are out of them that a large request may find no block: - /// freed small blocks wait in their classes, and what they free between - /// live ones is holes. + /// free blocks wait in their slabs and the cores' caches, and what is + /// freed between live blocks is holes. pub fn low(&self) -> bool { let total = self.total.load(Ordering::Relaxed); self.live() > total / 4 * 3 @@ -871,8 +967,8 @@ impl Heap { /// The bytes no block was carved from, the reserve's with the main /// bins', as the lock last left them: what a large request can surely - /// still find, short of the holes between live blocks and the freed - /// small blocks their classes keep. A cache that may grow asks it + /// still find, short of the holes between live blocks and the free + /// blocks the slabs keep. A cache that may grow asks it /// without taking the lock. pub fn room(&self) -> usize { self.room.load(Ordering::Relaxed) @@ -947,17 +1043,8 @@ impl Heap { // CPU-local cache ownership is already exclusive to this core. let state = unsafe { &mut *self.state.get() }; while cache.counts[class] < BATCH { - let head = state.small[class]; - let block = if head.is_null() { - // SAFETY: the initialized heap is exclusively guarded; - // this class supplies its nonzero extent and alignment. - unsafe { carve_draining(state, SMALLEST << class, SMALL_ALIGNMENT) } - } else { - // SAFETY: the guarded class head is a complete free Small - // node previously published by matching deallocation. - state.small[class] = unsafe { (*head).next }; - head.cast() - }; + // SAFETY: the initialized heap is exclusively guarded. + let block = unsafe { slab_take(state, class) }; if block.is_null() { break; } @@ -991,12 +1078,7 @@ impl Heap { cache.counts[class] -= 1; let freed = cache.blocks[class][cache.counts[class]]; // SAFETY: a free block of this class that only the cache held. - unsafe { - freed.write(Small { - next: state.small[class], - }) - }; - state.small[class] = freed; + unsafe { slab_give(state, class, freed.cast()) }; } } cache.blocks[class][cache.counts[class]] = block.cast(); @@ -1134,6 +1216,8 @@ impl Heap { peak: state.peak, largest, extents: state.extents, + slabs: state.slabs, + slab_free: state.slab_free, carves: state.carves, large: state.large, } @@ -1220,16 +1304,8 @@ unsafe fn allocate_locked(state: &mut State, layout: Layout, class: Option(); - // SAFETY: the caller's block of this class, at least 16 bytes - // and 16-byte aligned, which it no longer accesses. - unsafe { - block.write(Small { - next: state.small[class], - }) - }; - state.small[class] = block; + // SAFETY: the caller's block of this class, which it no longer + // accesses. + unsafe { slab_give(state, class, pointer) }; } else { state.live -= layout.size(); state.count_large(layout.size(), false); @@ -1537,7 +1607,8 @@ unsafe fn carve(state: &mut State, pool: usize, size: usize, alignment: usize) - } /// [`carve`] from the main bins, then from the reserve for a large request, -/// giving the class lists back to the bins and trying both when that fails. +/// giving the classes' empty slabs back to the bins and trying both when +/// that fails. /// /// # Safety /// The heap's lock is held and `state` is initialized. @@ -1551,27 +1622,232 @@ unsafe fn carve_draining(state: &mut State, size: usize, alignment: usize) -> *m if !block.is_null() { return block; } - for class in 0..CLASSES { - let mut head = core::mem::replace(&mut state.small[class], ptr::null_mut()); - while !head.is_null() { - // SAFETY: a freed block `carve` made for this class, which only - // this list owned. - unsafe { - let next = (*head).next; - release(state, head.cast()); - head = next; - } + // SAFETY: as above. + if unsafe { release_spares(state) } { + // SAFETY: as above. + let block = unsafe { carve(state, MAIN, size, alignment) }; + if !block.is_null() { + return block; } } // SAFETY: as above. - let block = unsafe { carve(state, MAIN, size, alignment) }; - if !block.is_null() { - return block; - } - // SAFETY: as above. unsafe { carve(state, RESERVE, size, alignment) } } +/// Give each class's empty slab back to the bins: whether there was any. +/// +/// # Safety +/// The heap's lock is held. +unsafe fn release_spares(state: &mut State) -> bool { + let mut released = false; + for class in 0..CLASSES { + let slab = core::mem::replace(&mut state.spare[class], ptr::null_mut()); + if !slab.is_null() { + // SAFETY: the caller's lock; a slab of this class in no list. + unsafe { release_slab(state, class, slab) }; + released = true; + } + } + released +} + +/// A block of `class` from its slabs, carving a slab when none has a free +/// block; null when the heap has no room for one. +/// +/// # Safety +/// The heap's lock is held and `state` is initialized. +unsafe fn slab_take(state: &mut State, class: usize) -> *mut u8 { + let bytes = SMALLEST << class; + let mut slab = state.partial[class]; + if slab.is_null() { + slab = core::mem::replace(&mut state.spare[class], ptr::null_mut()); + if slab.is_null() { + // SAFETY: the caller's lock and initialized state. + slab = unsafe { new_slab(state, class) }; + if slab.is_null() { + return ptr::null_mut(); + } + } + // SAFETY: the caller's lock; a slab of this class in no list. + unsafe { state.list_slab(class, slab) }; + } + // SAFETY: a listed slab, which has a free block: a freed one, or one + // never handed out below its capacity. + unsafe { + let block = if (*slab).free.is_null() { + let start = slab as usize - HEADER_BYTES; + let block = start + SLAB_FIRST + (*slab).fresh as usize * bytes; + (*slab).fresh += 1; + block as *mut u8 + } else { + let block = (*slab).free; + (*slab).free = (*block).next; + block.cast() + }; + (*slab).used += 1; + if (*slab).used == (*slab).capacity { + state.unlist_slab(class, slab); + } + state.slab_free -= bytes; + block + } +} + +/// Return `block` of `class` to its slab, and a slab left empty to the bins +/// unless its class keeps none. +/// +/// # Safety +/// The heap's lock is held and `block` is a block of `class` that +/// [`slab_take`] handed out and nothing accesses any more. +unsafe fn slab_give(state: &mut State, class: usize, block: *mut u8) { + let slab = slab_of(block, class); + // SAFETY: the slab the block was cut from, which holds it. + unsafe { + if (*slab).used == (*slab).capacity { + state.list_slab(class, slab); + } + let freed = block.cast::(); + freed.write(Small { next: (*slab).free }); + (*slab).free = freed; + (*slab).used -= 1; + state.slab_free += SMALLEST << class; + if (*slab).used == 0 { + state.unlist_slab(class, slab); + if state.spare[class].is_null() { + state.spare[class] = slab; + } else { + release_slab(state, class, slab); + } + } + } +} + +/// A new, empty slab of `class`, in no list; null when no extent holds one. +/// +/// # Safety +/// The heap's lock is held and `state` is initialized. +unsafe fn new_slab(state: &mut State, class: usize) -> *mut Slab { + let bytes = slab_bytes(class); + // SAFETY: the caller's lock and initialized state. + let mut start = unsafe { carve_slab(state, MAIN, bytes) }; + // SAFETY: as above. + if start == 0 && unsafe { release_spares(state) } { + // SAFETY: as above. + start = unsafe { carve_slab(state, MAIN, bytes) }; + } + if start == 0 { + // SAFETY: as above. + start = unsafe { carve_slab(state, RESERVE, bytes) }; + } + if start == 0 { + return ptr::null_mut(); + } + let slab = (start + HEADER_BYTES) as *mut Slab; + let capacity = (bytes - SLAB_FIRST) / (SMALLEST << class); + // SAFETY: the carved block's payload, which begins with the slab. + unsafe { + slab.write(Slab { + next: ptr::null_mut(), + previous: ptr::null_mut(), + free: ptr::null_mut(), + used: 0, + fresh: 0, + capacity: capacity as u32, + }); + } + state.slabs += 1; + state.slab_free += capacity * (SMALLEST << class); + slab +} + +/// Return empty `slab` of `class` to the bins. +/// +/// # Safety +/// The heap's lock is held; `slab` is in no list and none of its blocks is +/// out of it. +unsafe fn release_slab(state: &mut State, class: usize, slab: *mut Slab) { + // SAFETY: the caller's empty slab, the payload of a carved block. + unsafe { + state.slabs -= 1; + state.slab_free -= (*slab).capacity as usize * (SMALLEST << class); + release(state, slab.cast()); + } +} + +/// The blocks of each bin a slab's search looks at before it splits a +/// larger extent: a slab freed between live blocks leaves a hole of just its +/// size, which the next slab should take. +const SLAB_LOOKS: usize = 8; + +/// Where the payload of a slab of `bytes` starts in free `block`: past the +/// boundary tag at an address aligned to `bytes`, after a gap that is empty +/// or holds a block of its own. +/// +/// # Safety +/// The lock is held and `block` is a free block. +unsafe fn slab_fit(block: *mut Header, bytes: usize) -> Option { + let base = block as usize; + // SAFETY: the caller's free block. + let end = base + unsafe { size(block) }; + let mut start = aligned(base, bytes)?; + if start != base && start - base < MIN_BLOCK { + start = start.checked_add(bytes)?; + } + (start.checked_add(bytes)? <= end).then_some(start + HEADER_BYTES) +} + +/// A slab's block of `bytes` from `pool`'s bins, its boundary tag at an +/// address aligned to `bytes`: that address, or zero when none fits. The +/// smallest extents that hold it come first. +/// +/// # Safety +/// The heap's lock is held and `state` is initialized. +unsafe fn carve_slab(state: &mut State, pool: usize, bytes: usize) -> usize { + state.carves += 1; + // SAFETY: binned free blocks, with the caller's guard held. + let fits = |block| unsafe { slab_fit(block, bytes) }; + // Any extent of this size holds a slab, wherever it starts. + let surely = 2 * bytes + MIN_BLOCK; + let bins = &state.pools[pool]; + let (first_level, first_sub) = bin(bytes); + let (last_level, last_sub) = bin(surely); + let mut found = ptr::null_mut(); + 'search: for level in first_level..=last_level.min(LEVELS - 1) { + let mut subs = u32::from(bins.bins[level]); + if level == first_level { + subs &= u32::MAX << first_sub; + } + if level == last_level { + subs &= (1u32 << (last_sub + 1)) - 1; + } + while subs != 0 { + let sub = subs.trailing_zeros() as usize; + subs &= subs - 1; + // SAFETY: the caller's guard. + for block in unsafe { bin_blocks(bins.heads[level][sub]) }.take(SLAB_LOOKS) { + if fits(block).is_some() { + found = block; + break 'search; + } + } + } + } + if found.is_null() { + // SAFETY: the caller's guard. + found = unsafe { bins.find(surely, |block| fits(block).is_some()) }; + } + let Some(user) = (!found.is_null()).then(|| fits(found)).flatten() else { + return 0; + }; + // SAFETY: the guard; `found` is binned and `slab_fit` placed the slab + // in it. + unsafe { + state.remove(found); + take(state, found, user, bytes - HEADER_BYTES); + } + user - HEADER_BYTES +} + /// Page selection inside a CPU interval: the lowest payload address that /// fits, over every free block. Selection changes nothing until it fits. /// diff --git a/crates/stela-boot-core/src/heap/failure/tests.rs b/crates/stela-boot-core/src/heap/failure/tests.rs index 0a68bc7304..5f537fef90 100644 --- a/crates/stela-boot-core/src/heap/failure/tests.rs +++ b/crates/stela-boot-core/src/heap/failure/tests.rs @@ -1,8 +1,9 @@ use super::*; use core::{alloc::GlobalAlloc, fmt::Write}; -#[repr(align(4096))] -struct Ram([u8; 4096]); +/// Two of the smallest class's slabs, at their alignment. +#[repr(align(16384))] +struct Ram([u8; 32768]); struct Text { bytes: [u8; 512], used: usize, @@ -43,7 +44,7 @@ fn record(report: fmt::Arguments<'_>) { #[test] fn first_exhaustion_reports_once_without_allocating() { let heap = Heap::new().reporting_failures(record); - let mut ram = Ram([0; 4096]); + let mut ram = Ram([0; 32768]); // SAFETY: fresh exclusive aligned stack storage outlives this heap/model. unsafe { heap.initialize(ram.0.as_mut_ptr(), ram.0.len()) }; let layout = Layout::from_size_align(16, 16).unwrap(); @@ -54,12 +55,12 @@ fn first_exhaustion_reports_once_without_allocating() { let reported = REPORTED.with(|text| text.borrow().as_str().to_owned()); assert!(reported.contains("bytes=16 align=16 snapshot=locked-metadata")); assert!(reported.contains("live_estimate=")); - assert!(reported.contains("cpu_counters=relaxed total=4096")); + assert!(reported.contains("cpu_counters=relaxed total=32768")); assert!(reported.contains("largest=0\nHEAP AT FAILURE large classes 16:0M")); let first = heap.first_failure().unwrap(); assert_eq!((first.bytes, first.align), (16, 16)); let found = first.heap.unwrap(); - assert_eq!((found.total, found.largest), (4096, 0)); + assert_eq!((found.total, found.largest), (32768, 0)); assert!(found.live <= found.carved && found.carved <= found.total); // SAFETY: as above; this second failure must not report again, and the // first stays the one named. diff --git a/crates/stela-boot-core/src/heap/replay.rs b/crates/stela-boot-core/src/heap/replay.rs new file mode 100644 index 0000000000..454aec37ed --- /dev/null +++ b/crates/stela-boot-core/src/heap/replay.rs @@ -0,0 +1,393 @@ +//! A replay of a long session's allocations, shaped like the heap lines of +//! an 8-hour log of a 16 GB PC (4352 MiB heap): the live bytes of each size +//! class and each free-list bucket, long-lived blocks that turn over slowly, +//! blocks that live for seconds to minutes, and compile jobs whose scratch +//! comes and goes between them, with a Core Animation sized one each hour. +//! Everything is scaled down by [`SCALE`] in count, and buckets past 4 MiB in +//! size too, so the heap and its live share match the log's. +use super::*; +use std::vec::Vec; + +/// The log's heap, 4352 MiB, over this. +const SCALE: usize = 32; +/// Beats of 10 s in 8 hours. +const BEATS: usize = 8 * 360; +/// The log's live bytes the long-lived blocks take; seconds-to-minutes +/// blocks take most of the rest. +const LONG_PERCENT: usize = 84; +/// A beat's turnover of the long-lived blocks, in parts per 10 000. +const TURNOVER: u64 = 20; + +/// Live bytes by size class, 16 B doubling to 4 KiB (`classes=` in the +/// log's `HEAP` line at its busiest beat), in MiB. +const CLASS_MIB: [usize; CLASSES] = [24, 109, 100, 201, 415, 250, 260, 96, 129]; +/// Live free-list blocks by bucket, 4 KiB doubling (`4K:39736/105M`...): +/// count and MiB. +const BUCKETS: [(usize, usize); LARGE_BUCKETS] = [ + (39736, 105), + (9723, 84), + (1978, 44), + (3749, 129), + (461, 33), + (2825, 398), + (92, 25), + (86, 48), + (39, 51), + (15, 34), + (16, 73), + (8, 71), + (8, 155), + (2, 92), + (3, 220), + (1, 128), +]; + +/// A deterministic generator (xorshift64*). +struct Random(u64); + +impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + fn below(&mut self, bound: usize) -> usize { + (self.next() % bound.max(1) as u64) as usize + } +} + +/// A request of size class `class`. +fn class_size(random: &mut Random, class: usize) -> usize { + let top = SMALLEST << class; + let bottom = if class == 0 { 1 } else { top / 2 + 1 }; + bottom + random.below(top - bottom + 1) +} + +/// A request of bucket `bucket`, around the bucket's mean in the log (the +/// first holds page-aligned blocks of under 4 KiB too, taken here as just +/// over a page), scaled past 4 MiB. +fn bucket_size(random: &mut Random, bucket: usize) -> usize { + let (count, mib) = BUCKETS[bucket]; + let mean = (mib << 20) / count; + let size = mean / 2 + random.below(mean) / 16 * 16; + if bucket >= 11 { size / SCALE } else { size }.max(4097) +} + +struct Live { + pointer: *mut u8, + layout: Layout, + /// The beat it is freed at; `usize::MAX` for a long-lived block. + until: usize, +} + +struct Replay<'a> { + heap: &'a Heap, + random: Random, + /// The boot's tables of a megabyte or more, kept all session. + tables: Vec, + long: Vec, + timed: Vec, + failures: usize, +} + +impl Replay<'_> { + fn allocate(&mut self, size: usize, until: usize) -> Option { + let align = if self.random.below(64) == 0 { 64 } else { 16 }; + let layout = Layout::from_size_align(size, align).unwrap(); + // SAFETY: a nonzero layout on the initialized heap; freed once. + let pointer = unsafe { self.heap.alloc(layout) }; + if pointer.is_null() { + self.failures += 1; + return None; + } + // Touch it, as an owner does. + // SAFETY: the live allocation just made. + unsafe { pointer.write(0xa5) }; + Some(Live { + pointer, + layout, + until, + }) + } + + fn free(&self, live: Live) { + // SAFETY: a live allocation of this heap with its layout. + unsafe { self.heap.dealloc(live.pointer, live.layout) }; + } + + /// A small block's size: by the classes' live blocks. + fn small_size(&mut self) -> usize { + let counts = CLASS_MIB.map(|mib| mib << 10); + let blocks = |class: usize| counts[class] / (SMALLEST << class); + let total: usize = (0..CLASSES).map(blocks).sum(); + let mut pick = self.random.below(total); + let class = (0..CLASSES) + .position(|class| { + if pick < blocks(class) { + true + } else { + pick -= blocks(class); + false + } + }) + .unwrap(); + class_size(&mut self.random, class) + } + + fn keep(&mut self, size: usize) { + if let Some(live) = self.allocate(size, usize::MAX) { + self.long.push(live); + } + } + + fn timed(&mut self, size: usize, until: usize) { + if let Some(live) = self.allocate(size, until) { + self.timed.push(live); + } + } + + /// The long-lived profile, built as a boot builds it: its tables of a + /// megabyte or more first, largest first, then the rest interleaved, with + /// seconds-lived blocks between. + fn build(&mut self) { + let mut tables: Vec = Vec::new(); + let mut wanted: Vec = Vec::new(); + for (class, &mib) in CLASS_MIB.iter().enumerate() { + let mut bytes = (mib << 20) / SCALE * LONG_PERCENT / 100; + while bytes > 0 { + // The log counts a block by its class. + bytes = bytes.saturating_sub(SMALLEST << class); + wanted.push(class_size(&mut self.random, class)); + } + } + for (bucket, &(count, _)) in BUCKETS.iter().enumerate() { + let count = if bucket >= 11 { + count + } else { + // Rounded at random, so few blocks keep their bytes. + let scaled = count * LONG_PERCENT; + let whole = scaled / (100 * SCALE); + whole + usize::from(self.random.below(100 * SCALE) < scaled % (100 * SCALE)) + }; + for _ in 0..count { + let size = bucket_size(&mut self.random, bucket); + if bucket >= 8 { + tables.push(size); + } else { + wanted.push(size); + } + } + } + tables.sort_unstable_by(|a, b| b.cmp(a)); + // Shuffle the rest, so classes and buckets interleave. + for index in (1..wanted.len()).rev() { + let other = self.random.below(index + 1); + wanted.swap(index, other); + } + for size in tables { + if let Some(live) = self.allocate(size, usize::MAX) { + self.tables.push(live); + } + } + for size in wanted { + self.keep(size); + if self.random.below(8) == 0 { + let size = self.small_size(); + let until = 1 + self.random.below(30); + self.timed(size, until); + } + } + } + + /// One beat: the long-lived blocks turn over, seconds-to-minutes blocks + /// come and go, and `job` bytes of a compile's scratch are taken between + /// them and freed at the beat's end, a few of them kept. + fn beat(&mut self, beat: usize, job: usize) { + let turnover = self.long.len() * TURNOVER as usize / 10_000; + for _ in 0..turnover { + let index = self.random.below(self.long.len()); + let old = self.long.swap_remove(index); + let size = old.layout.size(); + self.free(old); + self.keep(size); + } + let mut scratch: Vec = Vec::new(); + let mut taken = 0; + let churn = 2000 / SCALE * 8; + let mut step = 0; + while step < churn || taken < job { + if step < churn { + let size = if self.random.below(64) == 0 { + let bucket = self.random.below(4); + bucket_size(&mut self.random, bucket) + } else { + self.small_size() + }; + let until = beat + 1 + self.random.below(60); + self.timed(size, until); + } + // A compile's scratch: mostly small IR nodes and sets, some + // arrays of up to a megabyte, a few larger. + for _ in 0..16 { + if taken >= job { + break; + } + let size = match self.random.below(100) { + 0 => ((2 << 20) + self.random.below(6 << 20)) / SCALE, + 1..=40 => 4097 + self.random.below(1 << 20), + _ => 16 + self.random.below(240), + }; + match self.allocate(size, beat) { + Some(live) => scratch.push(live), + // A compile that finds no memory stops: the heap's + // exhaustion, which the test counts. + None => { + taken = job; + break; + } + } + taken += size; + } + step += 1; + } + // A job keeps a few of its blocks: the compiled result. + for live in scratch { + if self.random.below(100) == 0 { + self.long.push(live); + } else { + self.free(live); + } + } + let mut index = 0; + while index < self.timed.len() { + if self.timed[index].until <= beat { + let live = self.timed.swap_remove(index); + self.free(live); + } else { + index += 1; + } + } + // A kept compile result goes again later. + while self.long.len() > 1 && self.random.below(4) == 0 { + let index = self.random.below(self.long.len()); + let old = self.long.swap_remove(index); + self.free(old); + } + } +} + +/// What the heap looks like at an hour's end. +#[derive(Clone, Copy, Debug)] +struct Hour { + live: usize, + carved: usize, + largest: usize, + extents: usize, + peak: usize, +} + +fn replay() -> (Vec, usize, usize) { + let bytes = (4352usize << 20) / SCALE; + let layout = Layout::from_size_align(bytes, 1 << 16).unwrap(); + // SAFETY: a nonzero layout; freed at the end. + let ram = unsafe { std::alloc::alloc(layout) }; + assert!(!ram.is_null()); + let heap = Heap::new(); + // SAFETY: exclusive backing for the replay, freed only after it. + unsafe { heap.initialize(ram, bytes) }; + // As the engine keeps it (`HEAP_RESERVE_SHARE`). + heap.reserve_tail(bytes / 16); + let mut replay = Replay { + heap: &heap, + random: Random(0x5eed_1234_abcd_0001), + tables: Vec::new(), + long: Vec::new(), + timed: Vec::new(), + failures: 0, + }; + replay.build(); + let mut hours = Vec::new(); + for beat in 0..BEATS { + let job = if beat % 360 == 180 { + // Core Animation's generic shader: 778 MiB at peak. + (778 << 20) / SCALE + } else if beat % 30 == 7 { + (60 << 20) / SCALE + } else { + 0 + }; + replay.beat(beat, job); + if beat % 360 == 359 { + let usage = heap.usage(); + hours.push(Hour { + live: usage.live, + carved: usage.carved, + largest: usage.largest, + extents: usage.extents, + peak: usage.peak, + }); + } + } + let failures = replay.failures; + let blocks = replay.tables.drain(..); + for live in blocks + .chain(replay.long.drain(..)) + .chain(replay.timed.drain(..)) + { + // SAFETY: each live block once, with its layout. + unsafe { heap.dealloc(live.pointer, live.layout) }; + } + let usage = heap.usage(); + let left = usage.carved; + // SAFETY: the heap holds nothing live; nothing uses its backing now. + unsafe { std::alloc::dealloc(ram, layout) }; + (hours, failures, left) +} + +#[test] +fn eight_hours_of_a_sessions_allocations_keep_holes_and_the_largest_extent_bounded() { + let total = (4352usize << 20) / SCALE; + let (hours, failures, left) = replay(); + let mib = |bytes: usize| bytes as f64 * SCALE as f64 / f64::from(1 << 20); + std::println!("failed allocations: {failures}"); + for (hour, at) in hours.iter().enumerate() { + std::println!( + "hour {}: live={:.0}M carved={:.0}M holes={:.0}M largest={:.0}M extents={} peak={:.0}M \ + (as at full scale)", + hour + 1, + mib(at.live), + mib(at.carved), + mib(at.carved - at.live), + mib(at.largest), + at.extents * SCALE, + mib(at.peak), + ); + } + assert_eq!(failures, 0, "allocations failed"); + // Everything freed returns to the bins, but each class's empty slab. + assert!(left <= CLASSES * SLAB_LARGEST, "{left} bytes left carved"); + let reserve = total / 16; + for at in &hours { + // Holes and the slabs' free blocks stay under a sixteenth of the heap. + assert!( + at.carved - at.live < total / 16, + "{:.0}M of holes", + mib(at.carved - at.live) + ); + // Free extents stay few: one per 16 KiB of heap at most. + assert!(at.extents < total >> 14, "{} extents", at.extents); + // The main part keeps an extent larger than the whole reserve. + assert!( + at.largest > reserve, + "largest {:.0}M, reserve {:.0}M", + mib(at.largest), + mib(reserve) + ); + } + // The last hour looks like the first: nothing grows with time. + let (first, last) = (hours[0], hours[hours.len() - 1]); + assert!(last.extents <= first.extents * 5 / 4); + assert!(last.carved - last.live <= first.carved - first.live); +} diff --git a/crates/stela-boot-core/src/heap/tests.rs b/crates/stela-boot-core/src/heap/tests.rs index af69aad80c..15364da4ea 100644 --- a/crates/stela-boot-core/src/heap/tests.rs +++ b/crates/stela-boot-core/src/heap/tests.rs @@ -13,24 +13,89 @@ fn usage_values(heap: &Heap) -> [usize; 5] { [u.total, u.live, u.carved, u.peak, u.largest] } +/// A heap of `bytes` aligned to the largest slab, leaked by the test. +fn slab_aligned(heap: &Heap, bytes: usize) -> usize { + let layout = Layout::from_size_align(bytes, SLAB_LARGEST).unwrap(); + // SAFETY: a nonzero layout; the test leaks this backing. + let ram = unsafe { std::alloc::alloc(layout) }; + // SAFETY: exclusive backing for the test's whole run. + unsafe { heap.initialize(ram, layout.size()) }; + ram as usize +} + #[test] -fn a_heap_whose_bins_are_nearly_empty_is_low_though_little_is_live() { +fn freed_small_blocks_return_their_slabs_to_the_bins_but_one_per_class() { let heap = Heap::new(); - let mut ram = backing(); - // SAFETY: exclusive test backing, kept through every exact free. - unsafe { heap.initialize(ram.0.as_mut_ptr(), ram.0.len()) }; + let start = slab_aligned(&heap, 512 << 10); let layout = Layout::from_size_align(4096, 16).unwrap(); - // SAFETY: valid layouts; the blocks return to their class, never to the - // bins, which is what this test measures. + let class = class(layout).unwrap(); + // SAFETY: valid layouts, each block freed once. unsafe { let blocks: Vec<*mut u8> = (0..31).map(|_| heap.alloc(layout)).collect(); assert!(blocks.iter().all(|block| !block.is_null())); + // Three slabs of 15, with no header per block. + assert_eq!(heap.usage().slabs, 3); + for &block in &blocks { + let slab = slab_of(block, class) as usize - HEADER_BYTES; + assert_eq!(slab % slab_bytes(class), 0); + assert!(block as usize >= slab + SLAB_FIRST); + assert!(block as usize + 4096 <= slab + slab_bytes(class)); + assert!(slab >= start); + } for block in blocks { heap.dealloc(block, layout); } } - assert_eq!(heap.usage().live, 0); - assert!(heap.low()); + let usage = heap.usage(); + assert_eq!(usage.live, 0); + assert_eq!((usage.slabs, usage.carved), (1, slab_bytes(class))); + assert_eq!(usage.slab_free, 15 * 4096); + assert!(!heap.low()); +} + +#[test] +fn a_freed_slab_leaves_a_hole_the_next_slab_takes() { + let heap = Heap::new(); + slab_aligned(&heap, 1 << 20); + let small = Layout::from_size_align(4096, 16).unwrap(); + let large = Layout::from_size_align(40 << 10, 16).unwrap(); + // SAFETY: valid layouts, each block freed once. + unsafe { + // Slabs between large blocks, then all but one slab's blocks freed: + // the empty slabs past the kept one leave holes of their size. + let mut smalls = Vec::new(); + let mut larges = Vec::new(); + for _ in 0..6 { + smalls.extend((0..15).map(|_| heap.alloc(small))); + larges.push(heap.alloc(large)); + } + assert!(smalls.iter().chain(&larges).all(|block| !block.is_null())); + assert_eq!(heap.usage().slabs, 6); + for block in smalls.drain(..) { + heap.dealloc(block, small); + } + assert_eq!(heap.usage().slabs, 1); + // New slabs fill those holes, not the free tail past the last + // large block. + let tail = *larges.iter().max().unwrap() as usize; + let again: Vec<*mut u8> = (0..60).map(|_| heap.alloc(small)).collect(); + assert!( + again + .iter() + .all(|&block| !block.is_null() && (block as usize) < tail) + ); + for block in again { + heap.dealloc(block, small); + } + for block in larges { + heap.dealloc(block, large); + } + } + let usage = heap.usage(); + assert_eq!( + (usage.live, usage.slabs, usage.carved), + (0, 1, SLAB_LARGEST) + ); } #[test] @@ -728,9 +793,9 @@ fn fragmented_selection_skips_earlier_extents_and_preserves_other_owners() { heap.dealloc(metadata, small); heap.dealloc(b, page); } - // The ordinary small-object cache keeps its own block, as before. + // The small block's class keeps its empty slab. assert_eq!(heap.usage().live, 0); - assert!(heap.usage().carved < 2 * PAGE_BYTES); + assert_eq!(heap.usage().carved, slab_bytes(class(small).unwrap())); } #[test] @@ -945,3 +1010,6 @@ fn the_room_is_what_no_block_was_carved_from_and_comes_back_when_freed() { } assert_eq!(heap.room(), total); } + +#[path = "replay.rs"] +mod replay; diff --git a/crates/stela-boot/src/engine/run.rs b/crates/stela-boot/src/engine/run.rs index 9434ef5c5d..3b9fdb4ac3 100644 --- a/crates/stela-boot/src/engine/run.rs +++ b/crates/stela-boot/src/engine/run.rs @@ -2511,10 +2511,11 @@ fn board_code( ) } -/// `HEAP small=310M large=62M 128K:352/73M cores=300M/20M classes=16:8M,…`: -/// the heap's live bytes in size-class blocks and free-list allocations, -/// the latter by power of two where a size holds a megabyte or more, each -/// tagged core's share, the tagged cores' bytes by size class, the failed +/// `HEAP small=310M large=62M 128K:352/73M cores=300M/20M classes=16:8M,… +/// slabs=4800/40M`: the heap's live bytes in size-class blocks and +/// free-list allocations, the latter by power of two where a size holds a +/// megabyte or more, each tagged core's share, the tagged cores' bytes by +/// size class, the size-class slabs and their free blocks' bytes, the failed /// allocations so far and whether the heap is low. fn heap_report(heap: &stela_boot_core::heap::Usage) { let large: usize = heap.large.iter().map(|&(_, bytes)| bytes).sum(); @@ -2546,6 +2547,8 @@ fn heap_report(heap: &stela_boot_core::heap::Usage) { .map(|(class, &bytes)| format!("{}:{}M", 16 << class, bytes >> 20)) .collect(); line.push_str(&format!(" classes={}", classes.join(","))); + // The size-class slabs, and the bytes of free blocks they keep. + line.push_str(&format!(" slabs={}/{}M", heap.slabs, heap.slab_free >> 20)); // Allocations that found no memory, which fallible callers survive, and // whether the heap is low enough that the engine gives memory back. line.push_str(&format!(