//! The kernel heap: what `Box`, `Vec` and the rest of `alloc` allocate from. //! //! Requests up to 2 KiB come from size classes, powers of two from 16 bytes, //! each a singly linked free list of slots carved from whole pages: an //! allocation or a free is a pop or a push. A slot is aligned to its size, so //! the class also meets any alignment up to it. Larger requests take pages //! straight from the buddy allocator. Pages carved into slots are not given //! back yet, and every core shares one lock: per-core caches of slots come //! when allocation shows up in a profile. use super::{PAGE, pages}; use crate::sync::SpinLock; use core::alloc::{GlobalAlloc, Layout}; const MIN_CLASS: usize = 16; const MAX_CLASS: usize = 2048; const CLASSES: usize = (MAX_CLASS / MIN_CLASS).trailing_zeros() as usize + 1; const NONE: usize = 0; struct Classes { heads: [usize; CLASSES], } static SLOTS: SpinLock = SpinLock::new(Classes { heads: [NONE; CLASSES], }); pub struct Heap; #[global_allocator] static HEAP: Heap = Heap; 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) } fn class_size(class: usize) -> usize { MIN_CLASS << class } // SAFETY: slots never overlap: each is handed out once until freed, and // pages come from the page allocator, which never hands out a block twice. unsafe impl GlobalAlloc for Heap { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let Some(class) = class(&layout) else { if layout.align() > PAGE << pages::MAX_ORDER { return core::ptr::null_mut(); } let order = pages::order_for(layout.size().max(layout.align())); if order > pages::MAX_ORDER { return core::ptr::null_mut(); } return pages::alloc(order).map_or(core::ptr::null_mut(), |a| a as *mut u8); }; let mut classes = SLOTS.lock(); if classes.heads[class] == NONE { let Some(page) = pages::alloc(0) else { return core::ptr::null_mut(); }; let size = class_size(class); // Thread the page's slots into the class's list, first slot first. for slot in (page..page + PAGE).step_by(size).rev() { // SAFETY: the slot lies in a page only this class owns. unsafe { (slot as *mut usize).write(classes.heads[class]) }; classes.heads[class] = slot; } } let slot = classes.heads[class]; // SAFETY: a free slot's first word links the next. classes.heads[class] = unsafe { (slot as *const usize).read() }; slot as *mut u8 } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let Some(class) = class(&layout) else { pages::free(ptr as usize, pages::order_for(layout.size().max(layout.align()))); return; }; let mut classes = SLOTS.lock(); // SAFETY: the slot is ours again; its first word becomes the link. unsafe { (ptr as *mut usize).write(classes.heads[class]) }; classes.heads[class] = ptr as usize; } }