//! The program's heap. Requests up to 2 KiB come from power-of-two size //! classes, free lists of slots carved from 64 KiB arenas: an allocation or //! a free is a pop or a push. Larger requests take memory from the kernel //! in whole pages; freed ones of up to 64 KiB are kept, by page count, for //! reuse, and larger ones given back (`unmap_memory`), kept only where the //! kernel cannot take them. use crate::sys; use core::alloc::{GlobalAlloc, Layout}; use core::cell::UnsafeCell; use core::sync::atomic::{AtomicBool, Ordering}; use pinnacle_abi::{ERROR, call}; const PAGE: usize = 4096; const MIN_CLASS: usize = 16; const MAX_CLASS: usize = 2048; const CLASSES: usize = (MAX_CLASS / MIN_CLASS).trailing_zeros() as usize + 1; const ARENA: usize = 64 * 1024; /// Freed large blocks, by page count up to this. const LARGE_KEPT: usize = 1024; /// Freed blocks of more pages than this go back to the kernel: a program /// that decodes a large image now and then would otherwise hold each. const KEPT_ALWAYS: usize = 16; struct State { classes: [usize; CLASSES], /// The rest of the current arena. arena: usize, arena_end: usize, large: [usize; LARGE_KEPT + 1], } /// The heap's state behind a lock: a program's threads share it. Taking it /// uncontended is one atomic swap; a thread that finds it taken spins a /// little, then yields its core. pub struct Heap { locked: AtomicBool, state: UnsafeCell, } // SAFETY: `state` is touched only with `locked` held. unsafe impl Sync for Heap {} struct Locked<'a>(&'a Heap); impl Heap { fn lock(&self) -> Locked<'_> { let mut spins = 0; while self.locked.swap(true, Ordering::Acquire) { spins += 1; if spins > 100 { crate::yield_now(); } else { core::hint::spin_loop(); } } Locked(self) } } impl Drop for Locked<'_> { fn drop(&mut self) { self.0.locked.store(false, Ordering::Release); } } #[global_allocator] static HEAP: Heap = Heap { locked: AtomicBool::new(false), state: UnsafeCell::new(State { classes: [0; CLASSES], arena: 0, arena_end: 0, large: [0; LARGE_KEPT + 1], }), }; fn from_kernel(size: usize) -> usize { let address = sys::call1(call::MAP_MEMORY, size as u64); if address == ERROR { 0 } else { address as usize } } fn class(layout: &Layout) -> Option { let size = layout .size() .max(layout.align()) .max(MIN_CLASS) .next_power_of_two(); (size <= MAX_CLASS).then(|| (size / MIN_CLASS).trailing_zeros() as usize) } // SAFETY: slots and blocks are handed out once until freed. unsafe impl GlobalAlloc for Heap { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let _locked = self.lock(); // SAFETY: the lock is held. let state = unsafe { &mut *self.state.get() }; let Some(class) = class(&layout) else { let pages = layout.size().div_ceil(PAGE); if layout.align() > PAGE { return core::ptr::null_mut(); } if pages <= LARGE_KEPT && state.large[pages] != 0 { let block = state.large[pages]; // SAFETY: a kept block's first word links the next. state.large[pages] = unsafe { *(block as *const usize) }; // SAFETY: the block is ours again; the kernel gave it zeroed // and a caller may expect nothing, but `alloc_zeroed` does. unsafe { core::ptr::write_bytes(block as *mut u8, 0, pages * PAGE) }; return block as *mut u8; } return from_kernel(pages * PAGE) as *mut u8; }; if state.classes[class] == 0 { let size = MIN_CLASS << class; // A slot is aligned to its size, so its class meets any alignment // up to it. state.arena = state.arena.next_multiple_of(size); if state.arena_end.saturating_sub(state.arena) < size { state.arena = from_kernel(ARENA); if state.arena == 0 { return core::ptr::null_mut(); } state.arena_end = state.arena + ARENA; } let slot = state.arena; state.arena += size; return slot as *mut u8; } let slot = state.classes[class]; // SAFETY: a free slot's first word links the next. state.classes[class] = unsafe { *(slot as *const usize) }; slot as *mut u8 } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let _locked = self.lock(); // SAFETY: the lock is held. let state = unsafe { &mut *self.state.get() }; match class(&layout) { Some(class) => { // SAFETY: the slot is ours again; its first word links. unsafe { *(ptr as *mut usize) = state.classes[class] }; state.classes[class] = ptr as usize; } None => { let pages = layout.size().div_ceil(PAGE); if pages > KEPT_ALWAYS && sys::call1(call::UNMAP_MEMORY, ptr as u64) != ERROR { return; } if pages <= LARGE_KEPT { // SAFETY: as above. unsafe { *(ptr as *mut usize) = state.large[pages] }; state.large[pages] = ptr as usize; } } } } }