diff --git a/crates/stela-boot-core/src/heap.rs b/crates/stela-boot-core/src/heap.rs index c54a0686ee..e6cd516979 100644 --- a/crates/stela-boot-core/src/heap.rs +++ b/crates/stela-boot-core/src/heap.rs @@ -37,7 +37,10 @@ use core::{ // Explicit, so the NVIDIA LUT fixture can compile this file by path. #[path = "heap/failure.rs"] mod failure; +#[path = "heap/stop.rs"] +mod stop; pub use failure::{FailedHeap, Failure}; +pub use stop::StopCounts; #[path = "heap/tally.rs"] pub mod tally; @@ -622,10 +625,14 @@ pub struct Heap { /// The heap's bytes not carved, the reserve's with the main bins'. room: AtomicUsize, waits: AtomicU64, + /// The processors that stop, and what they allocate from ([`stop`]). + stop: stop::Stop, } // SAFETY: all list/header mutations use the real acquire/release exclusion. // UEFI callers mask local interrupts before acquiring the lock. Critical -// sections cannot migrate/block; NMI and fault handlers never reenter the heap. +// sections cannot migrate/block. NMI and fault handlers reenter the heap only +// on the way to a stop, after `Heap::stop_on`: they then skip their core's +// cache and never wait for the lock without bound (`stop`). unsafe impl Sync for Heap {} impl Default for Heap { fn default() -> Self { @@ -664,6 +671,7 @@ impl Heap { carved: AtomicUsize::new(0), room: AtomicUsize::new(0), waits: AtomicU64::new(0), + stop: stop::Stop::new(), state: UnsafeCell::new(State { start: 0, end: 0, @@ -927,7 +935,9 @@ impl Heap { { return ptr::null_mut(); } - let guard = self.lock(); + let Some(guard) = self.lock_or_stop() else { + return ptr::null_mut(); + }; // SAFETY: acquire/release exclusion, as for ordinary allocation. let state = unsafe { &mut *self.state.get() }; if !state.ready { @@ -1151,7 +1161,9 @@ impl Heap { /// Adjacent frames may need an intervening allocation header when /// allocated separately, so this is not a reservation or allocation count. pub fn available_page_frames_in(&self, allowed: Range) -> usize { - let _guard = self.lock(); + let Some(_guard) = self.lock_or_stop() else { + return 0; + }; // SAFETY: the guard keeps the free blocks and their bins stable. let state = unsafe { &*self.state.get() }; let (first_level, _) = bin(PAGE_BYTES + HEADER_BYTES); @@ -1175,7 +1187,9 @@ impl Heap { /// Start a new high-water mark of the carved bytes, for /// [`Self::marked_peak`]: the bytes carved now. pub fn mark(&self) -> usize { - let _guard = self.lock(); + let Some(_guard) = self.lock_or_stop() else { + return self.carved.load(Ordering::Relaxed); + }; // SAFETY: the guard excludes every other state access. let state = unsafe { &mut *self.state.get() }; state.marked_peak = state.carved; @@ -1184,14 +1198,20 @@ impl Heap { /// The most bytes carved at once since the last [`Self::mark`]. pub fn marked_peak(&self) -> usize { - let _guard = self.lock(); + let Some(_guard) = self.lock_or_stop() else { + return 0; + }; // SAFETY: the guard excludes metadata writers. unsafe { (*self.state.get()).marked_peak } } - /// The heap's usage, walking the free list for its largest extent. + /// The heap's usage, walking the free list for its largest extent; on + /// a stopping processor that cannot have the lock, the counts the lock + /// last left. pub fn usage(&self) -> Usage { - let _guard = self.lock(); + let Some(_guard) = self.lock_or_stop() else { + return self.usage_unlocked(); + }; // SAFETY: the guard excludes metadata writers throughout; no state // reference escapes it. let state = unsafe { &*self.state.get() }; @@ -1317,6 +1337,15 @@ unsafe fn allocate_locked(state: &mut State, layout: Layout, class: Option *mut u8 { + if self.stopping() { + // SAFETY: the caller's GlobalAlloc contract. + let block = unsafe { self.stop_alloc(layout) }; + if block.is_null() { + self.failures.fetch_add(1, Ordering::Relaxed); + failure::report(self, layout); + } + return block; + } allocation_begins(); let class = class(layout); let cpu = self.cpu(); @@ -1348,6 +1377,10 @@ unsafe impl GlobalAlloc for Heap { block } unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { + if self.stopping() { + // SAFETY: the caller's GlobalAlloc contract. + return unsafe { self.stop_dealloc(pointer, layout) }; + } let class = class(layout); if let Some(cpu) = self.cpu() { self.count_own(cpu, layout, class, false); @@ -1382,6 +1415,10 @@ unsafe impl GlobalAlloc for Heap { } unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + if self.stopping() { + // SAFETY: the caller's GlobalAlloc contract. + return unsafe { self.stop_realloc(pointer, layout, new_size) }; + } // SAFETY: GlobalAlloc's realloc contract guarantees that this size // rounded to the original alignment fits in isize. let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; diff --git a/crates/stela-boot-core/src/heap/stop.rs b/crates/stela-boot-core/src/heap/stop.rs new file mode 100644 index 0000000000..509ca706ae --- /dev/null +++ b/crates/stela-boot-core/src/heap/stop.rs @@ -0,0 +1,322 @@ +//! The heap at a stop. A stop can begin anywhere: in an NMI or a fault that +//! interrupted its processor inside the heap, holding the lock or halfway +//! through the processor's own cache, or while another processor that +//! never runs again holds the lock. Its report allocates all the same: its +//! text, the screen, the log's store. A lock that spins without end would +//! then hang the stop with nothing on the screen. +//! +//! So once a processor says it stops ([`Heap::stop_on`]), its allocations +//! skip its cache, try the lock [`SPINS`] times at most, and take from a +//! reserve carved while the boot ran ([`Heap::keep_stop_reserve`]) when the +//! lock stays held; once the lock was held that long, one try each. Its +//! frees of reserve blocks do nothing, and those of heap blocks the lock +//! refuses are dropped and counted. Diagnostics that read the heap under +//! its lock answer from the counts the lock last left. Processors that do +//! not stop are unchanged, and a heap where no stop began costs one load +//! per call. +use super::{ + Guard, Heap, LARGE_BUCKETS, Usage, aligned, allocate_locked, class, release, slab_give, +}; +use core::{ + alloc::Layout, + ptr, + sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}, +}; + +/// The stopping processors a stop names one by one; with more, every +/// processor's calls are a stop's. +const PROCESSORS: usize = 16; +const NONE: u32 = u32::MAX; +/// Tries of the lock a stopping processor makes before it takes from the +/// reserve: some milliseconds, far more than any holder that still runs +/// keeps it. +pub(super) const SPINS: u32 = 1 << 16; + +pub(super) struct Stop { + began: AtomicBool, + /// The `fn() -> u32` that names the calling processor; 0 before a stop. + identity: AtomicUsize, + processors: [AtomicU32; PROCESSORS], + /// More processors stopped than `processors` holds. + every: AtomicBool, + /// The reserve, and its next free byte; `end` 0 without one. + start: AtomicUsize, + end: AtomicUsize, + next: AtomicUsize, + /// A stopping processor found the lock held for all its tries. + lock_lost: AtomicBool, + /// Allocations the reserve served, and frees the stop dropped. + reserved: AtomicU64, + dropped: AtomicU64, +} + +impl Stop { + pub(super) const fn new() -> Self { + Self { + began: AtomicBool::new(false), + identity: AtomicUsize::new(0), + processors: [const { AtomicU32::new(NONE) }; PROCESSORS], + every: AtomicBool::new(false), + start: AtomicUsize::new(0), + end: AtomicUsize::new(0), + next: AtomicUsize::new(0), + lock_lost: AtomicBool::new(false), + reserved: AtomicU64::new(0), + dropped: AtomicU64::new(0), + } + } + + fn identity(&self) -> Option { + let identity = self.identity.load(Ordering::Acquire); + // SAFETY: only `stop_on` stores a nonzero value, a `fn() -> u32`. + (identity != 0).then(|| unsafe { core::mem::transmute:: u32>(identity) }()) + } +} + +/// What a stop took from the heap ([`Heap::stop_counts`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct StopCounts { + /// Allocations the reserve served, as the lock was held. + pub reserved: u64, + /// Bytes of the reserve taken, and its size. + pub reserve_used: usize, + pub reserve_bytes: usize, + /// Frees dropped, as the lock was held. + pub dropped: u64, +} + +impl Heap { + /// From now on the calling processor stops: its allocations never wait + /// for the lock without end ([`self`](super::stop)). `identity` names + /// the calling processor, the same on every call there and different + /// on every other; the first stop's is kept. Allocates nothing and + /// takes no lock, so any stop path may call it first, an NMI's too. + pub fn stop_on(&self, identity: fn() -> u32) { + let stop = &self.stop; + let _ = stop.identity.compare_exchange( + 0, + identity as usize, + Ordering::AcqRel, + Ordering::Acquire, + ); + let Some(me) = stop.identity() else { + return; + }; + let named = stop.processors.iter().any(|slot| { + slot.load(Ordering::Relaxed) == me + || slot + .compare_exchange(NONE, me, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + }); + if !named { + stop.every.store(true, Ordering::Release); + } + stop.began.store(true, Ordering::Release); + } + + /// Carve the reserve a stop allocates from while the lock is held, + /// `bytes` long, once; whether the heap had it. Call while the boot + /// runs, once the heap is set up. + pub fn keep_stop_reserve(&self, bytes: usize) -> bool { + let stop = &self.stop; + if stop.end.load(Ordering::Acquire) != 0 { + return true; + } + let Ok(layout) = Layout::from_size_align(bytes.max(1), super::PAGE_BYTES) else { + return false; + }; + // SAFETY: a nonzero layout; the block is the stop's for the boot. + let block = unsafe { core::alloc::GlobalAlloc::alloc(self, layout) }; + if block.is_null() { + return false; + } + stop.start.store(block as usize, Ordering::Relaxed); + stop.next.store(block as usize, Ordering::Relaxed); + stop.end + .store(block as usize + layout.size(), Ordering::Release); + true + } + + /// What stops took from the heap so far. + pub fn stop_counts(&self) -> StopCounts { + let stop = &self.stop; + let start = stop.start.load(Ordering::Relaxed); + StopCounts { + reserved: stop.reserved.load(Ordering::Relaxed), + reserve_used: stop.next.load(Ordering::Relaxed) - start, + reserve_bytes: stop.end.load(Ordering::Relaxed).saturating_sub(start), + dropped: stop.dropped.load(Ordering::Relaxed), + } + } + + /// Whether the calling processor stops: one load while no stop began. + pub(super) fn stopping(&self) -> bool { + let stop = &self.stop; + if !stop.began.load(Ordering::Acquire) { + return false; + } + if stop.every.load(Ordering::Relaxed) { + return true; + } + let Some(me) = stop.identity() else { + return false; + }; + stop.processors + .iter() + .any(|slot| slot.load(Ordering::Relaxed) == me) + } + + /// The lock for a stopping processor, after [`SPINS`] tries at most. + pub(super) fn stop_lock(&self) -> Option> { + let tries = match self.stop.lock_lost.load(Ordering::Relaxed) { + true => 1, + false => SPINS, + }; + for _ in 0..tries { + if !self.held.load(Ordering::Relaxed) + && let Some(guard) = self.try_lock() + { + return Some(guard); + } + core::hint::spin_loop(); + } + self.stop.lock_lost.store(true, Ordering::Relaxed); + None + } + + /// The lock: waited for as ever, or as a stop does + /// ([`Self::stop_lock`]) on a stopping processor. + pub(super) fn lock_or_stop(&self) -> Option> { + match self.stopping() { + true => self.stop_lock(), + false => Some(self.lock()), + } + } + + pub(super) fn in_reserve(&self, pointer: *mut u8) -> bool { + let at = pointer as usize; + let stop = &self.stop; + stop.end.load(Ordering::Acquire) > at && at >= stop.start.load(Ordering::Relaxed) + } + + fn take_reserve(&self, layout: Layout) -> *mut u8 { + let stop = &self.stop; + let end = stop.end.load(Ordering::Acquire); + let mut next = stop.next.load(Ordering::Relaxed); + loop { + let Some(after) = aligned(next, layout.align()) + .and_then(|at| Some((at, at.checked_add(layout.size().max(1))?))) + .filter(|&(_, after)| after <= end) + else { + return ptr::null_mut(); + }; + match stop.next.compare_exchange_weak( + next, + after.1, + Ordering::AcqRel, + Ordering::Relaxed, + ) { + Ok(_) => { + stop.reserved.fetch_add(1, Ordering::Relaxed); + return after.0 as *mut u8; + } + Err(now) => next = now, + } + } + } + + /// A stopping processor's allocation: from the heap under its lock, + /// else from the reserve; null when neither has room. + /// + /// # Safety + /// As `GlobalAlloc::alloc`. + pub(super) unsafe fn stop_alloc(&self, layout: Layout) -> *mut u8 { + if let Some(guard) = self.stop_lock() { + // SAFETY: the guard owns the state; class matches the layout. + let block = unsafe { allocate_locked(&mut *self.state.get(), layout, class(layout)) }; + drop(guard); + if !block.is_null() { + return block; + } + } + self.take_reserve(layout) + } + + /// A stopping processor's free: nothing for a reserve block; a heap + /// block goes back under the lock, or is dropped where the lock stays + /// held. A size-class block goes to its slab, never to this + /// processor's cache, which the stop may have interrupted. + /// + /// # Safety + /// As `GlobalAlloc::dealloc`. + pub(super) unsafe fn stop_dealloc(&self, pointer: *mut u8, layout: Layout) { + if self.in_reserve(pointer) { + return; + } + let Some(_guard) = self.stop_lock() else { + self.stop.dropped.fetch_add(1, Ordering::Relaxed); + return; + }; + // SAFETY: the guard owns the state until this borrow ends. + let state = unsafe { &mut *self.state.get() }; + // A block a core's cache handed out is not in `state.live`. + if let Some(class) = class(layout) { + state.live = state.live.saturating_sub(super::SMALLEST << class); + // SAFETY: the caller's block of this class, which it no longer + // accesses. + unsafe { slab_give(state, class, pointer) }; + } else { + state.live = state.live.saturating_sub(layout.size()); + state.count_large(layout.size(), false); + // SAFETY: the caller's live free-list block; the lock is held. + unsafe { release(state, pointer) }; + } + } + + /// A stopping processor's resize: a size-class block that keeps its + /// class stays; any other moves to a new allocation. + /// + /// # Safety + /// As `GlobalAlloc::realloc`. + pub(super) unsafe fn stop_realloc( + &self, + pointer: *mut u8, + layout: Layout, + new_size: usize, + ) -> *mut u8 { + // SAFETY: GlobalAlloc's realloc contract. + let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; + let old_class = class(layout); + if !self.in_reserve(pointer) && old_class.is_some() && old_class == class(new_layout) { + return pointer; + } + // SAFETY: as `GlobalAlloc::realloc`: a new block is disjoint, and + // only then is the old one freed. + unsafe { + let next = self.stop_alloc(new_layout); + if !next.is_null() { + ptr::copy_nonoverlapping(pointer, next, layout.size().min(new_size)); + self.stop_dealloc(pointer, layout); + } + next + } + } + + /// The usage the lock last left, for a stopping processor that cannot + /// have the lock: the bin walk's fields are zero. + pub(super) fn usage_unlocked(&self) -> Usage { + let total = self.total.load(Ordering::Relaxed); + Usage { + total, + live: self.live(), + carved: total.saturating_sub(self.room.load(Ordering::Relaxed)), + peak: 0, + largest: 0, + extents: 0, + slabs: 0, + slab_free: 0, + carves: 0, + large: [(0, 0); LARGE_BUCKETS], + } + } +} diff --git a/crates/stela-boot-core/src/heap/tests.rs b/crates/stela-boot-core/src/heap/tests.rs index 15364da4ea..ca4ccd7506 100644 --- a/crates/stela-boot-core/src/heap/tests.rs +++ b/crates/stela-boot-core/src/heap/tests.rs @@ -1013,3 +1013,118 @@ fn the_room_is_what_no_block_was_carved_from_and_comes_back_when_freed() { #[path = "replay.rs"] mod replay; + +std::thread_local! { + /// The test thread's processor, for stop mode's identity. + static PROCESSOR: core::cell::Cell = const { core::cell::Cell::new(0) }; +} + +fn processor() -> u32 { + PROCESSOR.with(core::cell::Cell::get) +} + +/// A processor that stops while its own interrupted context holds the +/// lock allocates from the reserve, frees nothing it cannot, and reads its +/// usage, all without waiting; once the lock is free it uses the heap. +/// Processors that do not stop wait for the lock as before. +#[test] +fn a_stop_allocates_while_the_lock_is_held_and_never_waits() { + let heap = Heap::new(); + slab_aligned(&heap, 1 << 20); + assert!(heap.keep_stop_reserve(64 << 10)); + let small = Layout::from_size_align(48, 16).unwrap(); + let large = Layout::from_size_align(8 << 10, 64).unwrap(); + // SAFETY: valid layouts; each block is freed once with its layout. + unsafe { + let before = heap.alloc(small); + let big_before = heap.alloc(large); + assert!(!before.is_null() && !big_before.is_null()); + let live = heap.usage().live; + PROCESSOR.with(|id| id.set(7)); + heap.stop_on(processor); + assert!(heap.stopping()); + // The interrupted context holds the lock. + let held = heap.lock(); + let a = heap.alloc(small); + let b = heap.alloc(large); + assert!(heap.in_reserve(a) && heap.in_reserve(b)); + assert_eq!(b as usize % 64, 0); + a.write_bytes(0xa5, 48); + b.write_bytes(0x5a, 8 << 10); + // A resize moves within the reserve and keeps the bytes. + let grown = heap.realloc(a, small, 200); + assert!(heap.in_reserve(grown) && grown != a); + assert_eq!(*grown.add(47), 0xa5); + // Frees of reserve blocks do nothing; a heap block is dropped. + heap.dealloc(b, large); + heap.dealloc(before, small); + let counts = heap.stop_counts(); + assert_eq!((counts.reserved, counts.dropped), (3, 1)); + assert!(counts.reserve_used > (8 << 10) + 48 + 200); + assert_eq!(counts.reserve_bytes, 64 << 10); + // Usage answers from the counts the lock last left. + let usage = heap.usage(); + assert_eq!((usage.live, usage.largest), (live, 0)); + // More than the reserve holds: null, never a wait. + assert!( + heap.alloc(Layout::from_size_align(80 << 10, 16).unwrap()) + .is_null() + ); + drop(held); + // The lock is free again: the heap serves and takes back blocks. + let c = heap.alloc(small); + assert!(!c.is_null() && !heap.in_reserve(c)); + heap.dealloc(c, small); + heap.dealloc(big_before, large); + let usage = heap.usage(); + assert_eq!(usage.live, live - (8 << 10)); + assert!(usage.largest > 0); + assert_eq!(heap.stop_counts().dropped, 1); + } + // Another processor is not stopping: it waits for the lock as ever. + let other = thread::scope(|scope| { + scope + .spawn(|| { + PROCESSOR.with(|id| id.set(8)); + assert!(!heap.stopping()); + // SAFETY: a valid layout, freed once. + unsafe { + let block = heap.alloc(small); + let in_reserve = heap.in_reserve(block); + heap.dealloc(block, small); + in_reserve + } + }) + .join() + .unwrap() + }); + assert!(!other); +} + +/// A stop with no reserve still never waits: an allocation the lock +/// refuses is null, and counted as a failure. +#[test] +fn a_stop_without_a_reserve_fails_instead_of_waiting() { + let heap = Heap::new(); + slab_aligned(&heap, 512 << 10); + let layout = Layout::from_size_align(64, 16).unwrap(); + // SAFETY: a valid layout, freed once. + unsafe { + let block = heap.alloc(layout); + heap.dealloc(block, layout); + } + assert!(!heap.stopping()); + PROCESSOR.with(|id| id.set(3)); + heap.stop_on(processor); + let held = heap.lock(); + // SAFETY: a valid layout. + assert!(unsafe { heap.alloc(layout) }.is_null()); + assert_eq!(heap.failures(), 1); + drop(held); + // SAFETY: a valid layout, freed once. + unsafe { + let block = heap.alloc(layout); + assert!(!block.is_null()); + heap.dealloc(block, layout); + } +} diff --git a/crates/stela-boot/src/engine/interrupts.rs b/crates/stela-boot/src/engine/interrupts.rs index b1745cbc61..7edd5a8ae3 100644 --- a/crates/stela-boot/src/engine/interrupts.rs +++ b/crates/stela-boot/src/engine/interrupts.rs @@ -773,6 +773,9 @@ pub(crate) unsafe fn observe_descriptors() -> Descriptors { /// Report an x86 exception that is a Stela failure, never a guest event. pub fn fatal(frame: &Frame) -> ! { + // The exception may have interrupted the heap here, holding its lock or + // halfway through this processor's cache: the report below allocates. + output::heap_stops(); // A watcher's NMI after the boot stopped names no new failure: the // stop's reason stays the one shown. if frame.vector == 2 { diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index ce5a772eb0..e7c4ab8977 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -249,6 +249,7 @@ fn start(handoff: u64) -> Started { // every native root for the complete engine lifetime. unsafe { crate::ALLOCATOR.initialize(heap as *mut u8, handoff.heap.bytes as usize) }; crate::ALLOCATOR.reserve_tail(handoff.heap.bytes as usize / HEAP_RESERVE_SHARE); + output::keep_stop_reserve(); super::large_blocks::install(); // SAFETY: this loader-owned private seed is held in the shared physmap, // exclusively consumed here before any native service is published. diff --git a/crates/stela-boot/src/main.rs b/crates/stela-boot/src/main.rs index 4d08ad7dc8..3384225383 100644 --- a/crates/stela-boot/src/main.rs +++ b/crates/stela-boot/src/main.rs @@ -290,6 +290,7 @@ fn main() -> Status { // SAFETY: fresh LOADER_DATA pages that Stela owns for the whole boot, // initialized before any allocation. unsafe { ALLOCATOR.initialize(heap.as_ptr(), heap_bytes) }; + output::keep_stop_reserve(); // SAFETY: the registered heap is the reserved WB identity extent. unsafe { native_memory::initialize(heap.as_ptr() as usize, heap.as_ptr() as u64, heap_bytes, 0) diff --git a/crates/stela-boot/src/output.rs b/crates/stela-boot/src/output.rs index 44fef6e56e..8086beb978 100644 --- a/crates/stela-boot/src/output.rs +++ b/crates/stela-boot/src/output.rs @@ -1096,6 +1096,8 @@ pub fn hypervisor_exit_port() -> bool { /// Report `code` on the hypervisor exit port, then halt. On a PC the screen /// keeps the output until the machine is powered off. pub fn terminate(code: u32) -> ! { + heap_stops(); + stop_heap_report(); arguments(format_args!( "STELA STOPPED code={code:#x}; power off to continue\n" )); @@ -1114,6 +1116,7 @@ pub fn terminate(code: u32) -> ! { /// (`stop_record::carry`). Call only while firmware boot services and its /// system table remain live. pub(crate) fn early_fatal(message: &str) -> ! { + heap_stops(); if let Claim::Later { first_here } = FIRST_STOP.claim(stopping_processor()) { later_stop(&message, first_here) } @@ -1133,6 +1136,46 @@ pub(crate) fn early_fatal(message: &str) -> ! { /// The boot's first stop: the one whose reason is shown and recorded. pub static FIRST_STOP: FirstStop = FirstStop::new(); +/// The heap's reserve for a stop whose processor, or another that never +/// runs again, holds the heap's lock (`stela_boot_core::heap::Heap::stop_on`): +/// the stop's text, screen and the log's last stores, a pending megabyte +/// of lines among them, with room to spare. +const STOP_HEAP_RESERVE: usize = 4 << 20; + +/// Carve the heap's stop reserve, once each heap is set up: the loader's +/// and the engine's. A heap without room for it is named in one line; a +/// stop then fails its allocations while the lock is held, never waits. +pub(crate) fn keep_stop_reserve() { + if !crate::ALLOCATOR.keep_stop_reserve(STOP_HEAP_RESERVE) { + arguments(format_args!( + "HEAP stop reserve of {} KiB not kept: the heap had no room; a stop while the \ + heap's lock is held fails its allocations\n", + STOP_HEAP_RESERVE >> 10 + )); + } +} + +/// From here this processor stops, and its allocations never wait for the +/// heap's lock without end: the stop may have interrupted the heap here, +/// or its holder may never run again. First in every stop path; it +/// allocates nothing and takes no lock. +pub(crate) fn heap_stops() { + crate::ALLOCATOR.stop_on(stopping_processor); +} + +/// One line when a stop found the heap's lock held and used its reserve +/// or dropped frees; none otherwise. +fn stop_heap_report() { + let counts = crate::ALLOCATOR.stop_counts(); + if counts.reserved != 0 || counts.dropped != 0 { + arguments(format_args!( + "HEAP the stop found the heap's lock held: {} allocations took {} of the {} bytes \ + of its reserve, {} frees were dropped\n", + counts.reserved, counts.reserve_used, counts.reserve_bytes, counts.dropped + )); + } +} + /// This processor's APIC ID, without the engine's per-processor state, which /// a stop before it exists has none of. fn stopping_processor() -> u32 { @@ -1149,6 +1192,7 @@ fn stopping_processor() -> u32 { /// screen and in the kept record. The processor that made the first stop /// goes back to its wait for the power button; any other halts. fn later_stop(message: &dyn core::fmt::Display, first_here: bool) -> ! { + heap_stops(); // Whatever guest lines the first stop has not written, as its // processor may be the one that stopped making progress. crate::engine::write_guest_output_at_stop(); @@ -1264,6 +1308,7 @@ fn stop_advice(reason: Option<&str>) -> &'static str { } pub fn fatal(message: impl core::fmt::Display) -> ! { + heap_stops(); if let Claim::Later { first_here } = FIRST_STOP.claim(stopping_processor()) { later_stop(&message, first_here) } diff --git a/crates/stela-boot/src/output/terminal.rs b/crates/stela-boot/src/output/terminal.rs index 11b46a064f..3c59214bf1 100644 --- a/crates/stela-boot/src/output/terminal.rs +++ b/crates/stela-boot/src/output/terminal.rs @@ -200,6 +200,8 @@ impl core::fmt::Display for Failed { } pub(crate) fn panic(info: &PanicInfo<'_>) -> ! { + // A panic inside the heap holds its lock; its report allocates. + super::heap_stops(); if PRINTING .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) .is_ok()