use crate::{
cache::CacheLine,
chunks::CHUNK_SHIFT,
region::{Entry, HUGE_PAGE_CHUNKS, Region},
size_class::{CLASSES, Class, MAX_SMALL, Request, STEP, TABLE_MAX, TABLE_STEPS, classify},
slab::{Block, List, Owned, Returns, Slab},
sync::{AtomicBool, AtomicPtr, AtomicU64, Ordering},
};
use core::{alloc::Layout, cell::Cell, fmt, marker::PhantomData, ptr, ptr::NonNull};
const SINGLE: usize = 0b1;
const MESSAGE_BYTES: usize = 512;
const MESSAGE_BLOCKS: usize = MESSAGE_BYTES / size_of::<usize>() - 2;
const MESSAGE_CLASS: Class = Class::for_size(MESSAGE_BYTES);
const OUTBOXES: usize = 32;
const BATCH_BYTES: usize = 4096;
const BATCH_BLOCKS: usize = BATCH_BYTES / size_of::<usize>() - 2;
const BATCH_CLASS: Class = Class::for_size(BATCH_BYTES);
const SPILL_BUDGET: usize = 1 << 20;
const OUTBOX_BYTES: usize = 64 << 10;
const MAINTENANCE_INTERVAL: u32 = 64;
const GROWTH_BUDGET: usize = 2 << 20;
const HUGE_CACHE: usize = 4;
const HUGE_CACHE_BLOCK: usize = 8 << 20;
const HUGE_CACHE_BYTES: usize = 16 << 20;
macro_rules! count {
($heap:expr, $event:ident, $n:expr) => {
#[cfg(feature = "metrics")]
$heap.private.events.add(crate::metrics::Event::$event, $n as u64);
};
}
const ZERO_CHECK_MIN: usize = 1024;
const fn reusable_anywhere(class: Class) -> bool {
class.reusable_anywhere() || class.index() == MESSAGE_CLASS.index()
}
const _: () = assert!(!reusable_anywhere(Class::from_index(0)));
const FLUSH_BATCH: usize = 512;
pub(crate) const BIN_SIZE: usize = size_of::<Bin>();
const BIN_OFFSETS: [u16; TABLE_STEPS] = {
let mut offsets = [0; TABLE_STEPS];
let mut step = 0;
while step < offsets.len() {
offsets[step] = (Class::from_table(step * STEP).index() * size_of::<Bin>()) as u16;
step += 1;
}
offsets
};
const HUGE_ZONE_CHUNKS: usize = 16;
const UNDERFLOW: u8 = 0b01;
const OVERFLOW: u8 = 0b10;
const MISSED: u8 = 0b100;
const REFILLED: u8 = 0b1000;
#[repr(C)]
struct Message {
next: *mut Block,
count: u32,
class: u32,
blocks: [*mut Block; MESSAGE_BLOCKS],
}
const MIXED: u32 = u32::MAX;
const _: () = assert!(size_of::<Message>() == MESSAGE_BYTES);
const _: () = assert!(MESSAGE_CLASS.block_size() == MESSAGE_BYTES);
#[repr(C)]
struct Batch {
next: *mut Self,
count: usize,
blocks: [*mut Block; BATCH_BLOCKS],
}
const _: () = assert!(size_of::<Batch>() == BATCH_BYTES);
const _: () = assert!(BATCH_CLASS.block_size() == BATCH_BYTES);
struct Bin {
top: Cell<*mut *mut Block>,
empty: Cell<u16>,
full: Cell<u16>,
capacity: Cell<u16>,
misses: Cell<u8>,
anywhere: Cell<bool>,
#[cfg(feature = "metrics")]
allocs: crate::metrics::Counter,
#[cfg(feature = "metrics")]
frees: crate::metrics::Counter,
}
struct Outbox {
dest: Cell<u32>,
message: Cell<*mut Message>,
bytes: Cell<u32>,
}
#[derive(Clone, Copy)]
struct Kept {
first: usize,
chunks: usize,
reused: bool,
}
impl Kept {
const NONE: Self = Self { first: 0, chunks: 0, reused: false };
}
struct Lists {
active: Cell<*const Slab>,
active_last: Cell<*const Slab>,
full: Cell<*const Slab>,
filled: Cell<u32>,
spill: Cell<*mut Batch>,
unspilled: Cell<bool>,
#[cfg(feature = "metrics")]
slabs: crate::metrics::Counter,
}
struct Shared {
_line: [CacheLine; 0],
claimed: AtomicBool,
inbox: AtomicPtr<Block>,
}
#[repr(C)]
struct Private {
_line: [CacheLine; 0],
id: Cell<u32>,
refills: Cell<u32>,
draining: Cell<bool>,
grown: Cell<usize>,
spilled: Cell<usize>,
base: Cell<*mut u8>,
span: Cell<usize>,
map: Cell<*const AtomicU64>,
slabs: Cell<*const Slab>,
region: Cell<*const Region<'static>>,
node: Cell<usize>,
cursor: Cell<usize>,
held: Cell<usize>,
runs: Cell<usize>,
big: Cell<bool>,
bins: [Bin; CLASSES],
slots: Cell<*mut *mut Block>,
outboxes: [Outbox; OUTBOXES],
kept: [Cell<Kept>; HUGE_CACHE],
classes: [Lists; CLASSES],
#[cfg(feature = "metrics")]
events: crate::metrics::HeapEvents,
}
pub(crate) struct HeapData {
shared: Shared,
private: Private,
}
impl fmt::Debug for HeapData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HeapData")
.field("claimed", &self.shared.claimed)
.field("inbox", &self.shared.inbox)
.finish_non_exhaustive()
}
}
unsafe impl Sync for HeapData {}
impl HeapData {
#[cfg(any(test, feature = "testing"))]
#[allow(clippy::missing_const_for_fn, reason = "loom atomics have no const constructors")]
pub(crate) fn new() -> Self {
Self {
shared: Shared {
_line: [],
claimed: AtomicBool::new(false),
inbox: AtomicPtr::new(ptr::null_mut()),
},
private: Private {
_line: [],
id: Cell::new(0),
refills: Cell::new(0),
draining: Cell::new(false),
grown: Cell::new(0),
spilled: Cell::new(0),
base: Cell::new(ptr::null_mut()),
span: Cell::new(0),
map: Cell::new(ptr::null()),
slabs: Cell::new(ptr::null()),
region: Cell::new(ptr::null()),
node: Cell::new(0),
cursor: Cell::new(0),
held: Cell::new(0),
runs: Cell::new(0),
big: Cell::new(false),
bins: [const {
Bin {
top: Cell::new(ptr::null_mut()),
empty: Cell::new(0),
full: Cell::new(0),
capacity: Cell::new(0),
misses: Cell::new(0),
anywhere: Cell::new(false),
#[cfg(feature = "metrics")]
allocs: crate::metrics::Counter::new(),
#[cfg(feature = "metrics")]
frees: crate::metrics::Counter::new(),
}
}; CLASSES],
slots: Cell::new(ptr::null_mut()),
outboxes: [const {
Outbox {
dest: Cell::new(0),
message: Cell::new(ptr::null_mut()),
bytes: Cell::new(0),
}
}; OUTBOXES],
kept: [const { Cell::new(Kept::NONE) }; HUGE_CACHE],
classes: [const {
Lists {
active: Cell::new(ptr::null()),
active_last: Cell::new(ptr::null()),
full: Cell::new(ptr::null()),
filled: Cell::new(0),
spill: Cell::new(ptr::null_mut()),
unspilled: Cell::new(false),
#[cfg(feature = "metrics")]
slabs: crate::metrics::Counter::new(),
}
}; CLASSES],
#[cfg(feature = "metrics")]
events: crate::metrics::HeapEvents::new(),
},
}
}
#[cfg(feature = "metrics")]
pub(crate) fn class_counts(&self, class: Class) -> (u64, u64, u64) {
let bin = self.bin(class);
(bin.allocs.get(), bin.frees.get(), self.lists(class).slabs.get())
}
#[cfg(feature = "metrics")]
pub(crate) const fn events(&self) -> &crate::metrics::HeapEvents {
&self.private.events
}
pub(crate) fn claim(&self, id: u32, region: &Region<'_>) -> bool {
let won = self.try_take();
if won {
self.adopt(id, region);
}
won
}
pub(crate) fn borrow(&self, id: u32, region: &Region<'_>) -> bool {
let won = self.try_take();
if won && self.private.region.get().is_null() {
self.adopt(id, region);
}
won
}
fn try_take(&self) -> bool {
!self.shared.claimed.load(Ordering::Relaxed) &&
self.shared
.claimed
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
}
fn adopt(&self, id: u32, region: &Region<'_>) {
let private = &self.private;
private.id.set(id);
private.region.set(ptr::from_ref(region).cast());
private.base.set(region.chunk_ptr(0));
private.span.set(region.span());
private.slabs.set(region.slabs_ptr());
private.map.set(region.map_ptr());
private.slots.set(region.bin_slots(id));
self.settle_on(region, region.current_node());
self.init_bins();
}
fn settle_on(&self, region: &Region<'_>, node: usize) {
self.private.node.set(node);
let home = region.home(self.slab_part(region, Class::from_index(0)));
if !home.contains(&self.private.cursor.get()) {
self.private.cursor.set(home.start);
}
}
fn is_big(&self) -> bool {
let size = self.private.held.get() + self.private.runs.get();
let low = if self.private.big.get() { HUGE_ZONE_CHUNKS / 4 } else { HUGE_ZONE_CHUNKS };
let big = size >= low;
self.private.big.set(big);
big
}
fn slab_part(&self, region: &Region<'_>, class: Class) -> usize {
let filled = self.lists(class).filled.get() > 0;
let dense = class.slab_chunks() == 1 || filled;
let huge = dense && (self.is_big() || (filled && region.is_big()));
region.part(self.private.node.get(), huge)
}
fn init_bins(&self) {
for (index, bin) in self.private.bins.iter().enumerate() {
let class = Class::from_index(index);
let end = self.bin_end(class);
if bin.top.get().is_null() {
bin.top.set(end);
}
debug_assert_eq!(bin.top.get(), end, "a released heap left blocks in a bin");
bin.empty.set(end.addr() as u16);
bin.misses.set(0);
bin.anywhere.set(reusable_anywhere(class));
self.set_capacity(class, class.bin_initial());
}
self.private.grown.set(0);
}
const fn bin_end(&self, class: Class) -> *mut *mut Block {
self.slots().wrapping_add(class.bin_start() + class.bin_max())
}
fn set_capacity(&self, class: Class, capacity: usize) {
let bin = self.bin(class);
assert!(self.bin_len(class) <= capacity && capacity <= class.bin_max());
bin.capacity.set(capacity as u16);
bin.full.set(self.bin_end(class).wrapping_sub(capacity).addr() as u16);
}
fn note_miss(&self, class: Class, kind: u8) -> bool {
let bin = self.bin(class);
let last = bin.misses.get() & (UNDERFLOW | OVERFLOW);
let refilled = if kind == UNDERFLOW { REFILLED } else { bin.misses.get() & REFILLED };
bin.misses.set(kind | MISSED | refilled);
let capacity = usize::from(bin.capacity.get());
if last == 0 || last == kind || capacity == class.bin_max() {
return false;
}
let grown = (capacity * 2).min(class.bin_max());
let bytes = (grown - capacity) * class.block_size();
if self.private.grown.get() + bytes > GROWTH_BUDGET {
return false;
}
self.private.grown.set(self.private.grown.get() + bytes);
self.set_capacity(class, grown);
count!(self, BinsGrown, 1);
true
}
const fn slots(&self) -> *mut *mut Block {
self.private.slots.get()
}
pub(crate) unsafe fn give_up(&self) {
let region = unsafe { self.region() };
unsafe { self.empty_caches(region) };
self.release_claim();
region.vacate();
}
pub(crate) fn release_claim(&self) {
self.shared.claimed.store(false, Ordering::Release);
}
pub(crate) fn is_claimed(&self) -> bool {
self.shared.claimed.load(Ordering::Relaxed)
}
pub(crate) fn has_mail(&self) -> bool {
!self.shared.inbox.load(Ordering::Relaxed).is_null()
}
pub(crate) unsafe fn post_block(&self, block: *mut Block) {
unsafe { self.post(block.map_addr(|addr| addr | SINGLE), block) };
}
unsafe fn post(&self, node: *mut Block, raw: *mut Block) {
let inbox = &self.shared.inbox;
let mut head = inbox.load(Ordering::Relaxed);
loop {
unsafe { (*raw).next = head };
match inbox.compare_exchange_weak(head, node, Ordering::Release, Ordering::Relaxed) {
Ok(_) => return,
Err(actual) => head = actual,
}
}
}
const fn lists(&self, class: Class) -> &Lists {
&self.private.classes[class.index()]
}
const fn head(&self, class: Class, list: List) -> &Cell<*const Slab> {
let lists = self.lists(class);
match list {
List::Active => &lists.active,
List::Full => &lists.full,
List::None => unreachable!(),
}
}
#[inline(always)]
const unsafe fn region(&self) -> &Region<'_> {
unsafe { &*self.private.region.get() }
}
#[inline(always)]
fn entry_of(&self, ptr: *const u8) -> Entry {
let index = (ptr.addr() - self.private.base.get().addr()) >> CHUNK_SHIFT;
Entry(unsafe { &*self.private.map.get().add(index) }.load(Ordering::Relaxed))
}
#[inline(always)]
fn bin(&self, class: Class) -> &Bin {
debug_assert!(class.index() < CLASSES);
unsafe { self.private.bins.get_unchecked(class.index()) }
}
#[inline(always)]
fn pop(&self, class: Class) -> Option<*mut Block> {
Self::pop_from(self.bin(class))
}
#[inline(always)]
fn pop_from(bin: &Bin) -> Option<*mut Block> {
let top = bin.top.get();
if top.addr() as u16 == bin.empty.get() {
return None;
}
bin.top.set(top.wrapping_add(1));
#[cfg(feature = "metrics")]
bin.allocs.add(1);
unsafe {
let block = *top;
core::hint::assert_unchecked(!block.is_null());
Some(block)
}
}
#[inline(always)]
fn push(&self, class: Class, block: *mut Block) -> bool {
Self::push_to(self.bin(class), block)
}
#[inline(always)]
fn push_to(bin: &Bin, block: *mut Block) -> bool {
let top = bin.top.get();
if top.addr() as u16 == bin.full.get() {
return false;
}
let top = top.wrapping_sub(1);
unsafe { *top = block };
bin.top.set(top);
true
}
fn bin_len(&self, class: Class) -> usize {
let end = self.bin_end(class);
(end.addr() - self.bin(class).top.get().addr()) / size_of::<usize>()
}
#[inline(always)]
pub(crate) unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if Class::is_table_request(layout) {
return unsafe { self.alloc_table(layout.size(), layout.align() > STEP) };
}
unsafe { self.alloc_general(layout) }
}
#[inline(always)]
pub(crate) unsafe fn alloc_table(&self, size: usize, wide: bool) -> *mut u8 {
if let Some(block) = self.pop_table(size, wide) {
return block;
}
unsafe { self.refill(Class::from_table(Self::table_step(size, wide) * STEP)) }.cast()
}
#[inline(always)]
pub(crate) fn pop_table(&self, size: usize, wide: bool) -> Option<*mut u8> {
debug_assert!(size <= TABLE_MAX);
let step = Self::table_step(size, wide);
let bin = unsafe {
let offset = *BIN_OFFSETS.get_unchecked(step);
&*self.private.bins.as_ptr().byte_add(usize::from(offset))
};
Self::pop_from(bin).map(<*mut Block>::cast)
}
#[inline(always)]
const fn table_step(size: usize, wide: bool) -> usize {
if wide { size.div_ceil(2 * STEP) * 2 } else { size.div_ceil(STEP) }
}
#[inline(never)]
unsafe fn alloc_general(&self, layout: Layout) -> *mut u8 {
match classify(layout) {
Some(Request::Small(class)) => {
unsafe { self.region() }.purge_if_due();
self.pop(class)
.unwrap_or_else(|| unsafe { self.refill(class) })
.cast()
}
Some(Request::Huge { chunks, align }) => unsafe { self.alloc_whole(chunks, align) },
None => ptr::null_mut(),
}
}
#[inline(never)]
unsafe fn alloc_whole(&self, chunks: usize, align: usize) -> *mut u8 {
let region = unsafe { self.region() };
let block = self.alloc_huge(region, chunks, align);
if !block.is_null() {
return block;
}
unsafe { self.flush(region) };
self.alloc_huge(region, chunks, align)
}
#[cold]
#[inline(never)]
unsafe fn refill(&self, class: Class) -> *mut Block {
count!(self, Refills, 1);
let region = unsafe { self.region() };
if unsafe { self.read_mail(region) } &&
let Some(block) = self.pop(class)
{
return block;
}
unsafe { self.maintain(region) };
if let Some(block) = self.pop(class) {
return block;
}
self.note_miss(class, UNDERFLOW);
if self.unspill(region, class) &&
let Some(block) = self.pop(class)
{
return block;
}
if self.fill(region, class) == 0 {
unsafe { self.flush(region) };
if self.fill(region, class) == 0 {
return ptr::null_mut();
}
}
self.pop(class).unwrap_or(ptr::null_mut())
}
unsafe fn maintain(&self, region: &Region<'_>) {
region.purge_if_due();
let refills = self.private.refills.get().wrapping_add(1);
self.private.refills.set(refills);
if refills.is_multiple_of(MAINTENANCE_INTERVAL) {
for outbox in &self.private.outboxes {
unsafe { self.post_outbox(region, outbox) };
}
for kept in &self.private.kept {
let block = kept.get();
if block.chunks != 0 && !block.reused {
kept.set(Kept::NONE);
region.free_chunks(block.first, block.chunks);
} else {
kept.set(Kept { reused: false, ..block });
}
}
for (index, bin) in self.private.bins.iter().enumerate() {
let class = Class::from_index(index);
let capacity = usize::from(bin.capacity.get());
if bin.misses.get() & MISSED == 0 && capacity > class.bin_initial() {
let shrunk = (capacity / 2).max(class.bin_initial());
unsafe { self.flush_bin(class, shrunk) };
self.set_capacity(class, shrunk);
count!(self, BinsShrunk, 1);
let bytes = (capacity - shrunk) * class.block_size();
self.private.grown.set(self.private.grown.get() - bytes);
}
let misses = bin.misses.get();
bin.misses.set(if misses & MISSED == 0 {
misses & !REFILLED
} else {
misses & !MISSED
});
let lists = self.lists(class);
if !lists.unspilled.replace(false) && !lists.spill.get().is_null() {
unsafe { self.return_spill(region, class, false) };
}
}
}
}
fn fill(&self, region: &Region<'_>, class: Class) -> usize {
let bin = self.bin(class);
let want = (usize::from(bin.capacity.get()) / 2).max(1);
let end = bin.top.get();
let first = end.wrapping_sub(want);
let mut got = 0;
while got < want {
let Some(slab) = (unsafe { self.lists(class).active.get().as_ref() }) else {
if unsafe { self.add_slab(region, class) } {
continue;
}
break;
};
let slab = unsafe { slab.owned() };
let mut slot = first.wrapping_add(got);
got += slab.take(want - got, |block| {
unsafe { *slot = block.cast() };
slot = slot.wrapping_add(1);
});
self.after_take(slab, class);
}
let top = end.wrapping_sub(got);
if got < want {
unsafe { ptr::copy(first, top, got) };
}
bin.top.set(top);
got
}
unsafe fn add_slab(&self, region: &Region<'_>, class: Class) -> bool {
let chunks = class.slab_chunks();
let part = self.slab_part(region, class);
let home = region.home(part);
let cursor = self.private.cursor.get();
let cursor = if home.contains(&cursor) { cursor } else { home.start };
let Some((first, zeroed)) = region.alloc_chunks_zeroed(chunks, chunks, cursor, part) else {
return false;
};
count!(self, SlabsAdded, 1);
#[cfg(feature = "metrics")]
self.lists(class).slabs.add(1);
region.set_owner(first, chunks, self.private.id.get(), class);
let slab = region.slab(first);
let owned = unsafe { slab.owned() };
unsafe { owned.init(class, region.chunk_ptr(first), zeroed) };
self.push_front(owned, List::Active);
if chunks == 1 && home.contains(&(first / 64)) {
self.private.cursor.set(first / 64);
}
true
}
fn after_take(&self, slab: Owned<'_>, class: Class) {
if slab.is_exhausted() {
self.move_to(slab, List::Full);
if slab.mark_filled() {
self.private.held.set(self.private.held.get() + class.slab_chunks());
let filled = &self.lists(class).filled;
filled.set(filled.get() + 1);
}
}
}
pub(crate) unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
let size = layout.size();
match classify(layout) {
Some(Request::Small(class)) if class.block_size() >= ZERO_CHECK_MIN => {
let (block, zeroed) = self.pop(class).map_or_else(
|| unsafe { self.take_zeroed(class) },
|block| (block.cast::<u8>(), false),
);
if !block.is_null() && !zeroed {
unsafe { block.write_bytes(0, size) };
}
block
}
Some(Request::Huge { chunks, align }) => {
let region = unsafe { self.region() };
let (mut block, mut zeroed) = self.alloc_huge_zeroed(region, chunks, align);
if block.is_null() {
unsafe { self.flush(region) };
(block, zeroed) = self.alloc_huge_zeroed(region, chunks, align);
}
if !block.is_null() && !zeroed {
unsafe { block.write_bytes(0, size) };
}
block
}
_ => {
let block = unsafe { self.alloc(layout) };
if !block.is_null() {
unsafe { block.write_bytes(0, size) };
}
block
}
}
}
#[cold]
unsafe fn take_zeroed(&self, class: Class) -> (*mut u8, bool) {
let region = unsafe { self.region() };
if self.has_mail() {
return (unsafe { self.refill(class) }.cast(), false);
}
unsafe { self.maintain(region) };
if let Some(block) = self.pop(class) {
return (block.cast(), false);
}
loop {
if let Some(slab) = unsafe { self.lists(class).active.get().as_ref() } {
let slab = unsafe { slab.owned() };
if let Some((block, zeroed)) = slab.take_one() {
self.after_take(slab, class);
#[cfg(feature = "metrics")]
{
self.bin(class).allocs.add(1);
if zeroed {
count!(self, ZeroedFresh, 1);
}
}
return (block, zeroed);
}
}
if !unsafe { self.add_slab(region, class) } {
return (unsafe { self.refill(class) }.cast(), false);
}
}
}
pub(crate) unsafe fn realloc(&self, ptr: NonNull<u8>, old: Layout, new_size: usize) -> *mut u8 {
let new = unsafe { Layout::from_size_align_unchecked(new_size, old.align()) };
let region = unsafe { self.region() };
match (classify(old), classify(new)) {
(Some(Request::Small(_)), Some(Request::Small(_))) => {
let size = self.entry_of(ptr.as_ptr()).class().block_size();
if new_size <= size && new_size >= size / 2 {
return ptr.as_ptr();
}
}
(
Some(Request::Huge { chunks: had, .. }),
Some(Request::Huge { chunks: wants, .. }),
) => {
let first = region.chunk_index(ptr.as_ptr());
if wants <= had {
if wants < had {
count!(self, HugeBytesFreed, (had - wants) << CHUNK_SHIFT);
region.set_huge(first, wants);
region.free_chunks(first + wants, had - wants);
region.purge_if_due();
}
return ptr.as_ptr();
}
if region.grow_in_place(first, had, wants) {
count!(self, HugeBytesAllocated, (wants - had) << CHUNK_SHIFT);
region.set_huge(first, wants);
return ptr.as_ptr();
}
}
_ => {}
}
let block = unsafe { self.alloc(new) };
if block.is_null() {
return block;
}
unsafe {
ptr::copy_nonoverlapping(ptr.as_ptr(), block, old.size().min(new_size));
self.dealloc(ptr, old);
}
block
}
#[inline(always)]
pub(crate) unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
if layout.size() <= MAX_SMALL {
unsafe { self.free_small(ptr.as_ptr().cast()) };
} else {
unsafe { self.free_huge(ptr, layout) };
}
}
#[inline(never)]
unsafe fn free_huge(&self, ptr: NonNull<u8>, layout: Layout) {
let region = unsafe { self.region() };
let Some(Request::Huge { chunks, .. }) = classify(layout) else {
return unsafe { region.dealloc(ptr, layout) };
};
let bytes = chunks << CHUNK_SHIFT;
self.private.runs.set(self.private.runs.get().saturating_sub(chunks));
count!(self, HugeFrees, 1);
count!(self, HugeBytesFreed, bytes);
if bytes <= HUGE_CACHE_BLOCK {
let held: usize =
self.private.kept.iter().map(|kept| kept.get().chunks << CHUNK_SHIFT).sum();
let empty = self.private.kept.iter().find(|kept| kept.get().chunks == 0);
if let Some(empty) = empty &&
held + bytes <= HUGE_CACHE_BYTES
{
let first = region.chunk_index(ptr.as_ptr());
empty.set(Kept { first, chunks, reused: true });
return;
}
}
region.free_chunks(region.chunk_index(ptr.as_ptr()), chunks);
region.purge_if_due();
}
#[inline(always)]
unsafe fn free_small(&self, block: *mut Block) {
unsafe { self.free_entry(block, self.entry_of(block.cast())) };
}
#[inline(always)]
pub(crate) unsafe fn free_unsized(&self, ptr: NonNull<u8>) {
let Some(entry) = self.entry_in_region(ptr.as_ptr()) else { return };
unsafe { self.free_with_entry(ptr, entry) };
}
#[inline(always)]
pub(crate) unsafe fn free_with_entry(&self, ptr: NonNull<u8>, entry: Entry) {
if let Some(chunks) = entry.huge_chunks() {
return unsafe {
self.free_huge(ptr, Layout::from_size_align_unchecked(chunks << CHUNK_SHIFT, 16))
};
}
unsafe { self.free_entry(ptr.as_ptr().cast(), entry) };
}
#[inline(always)]
fn entry_in_region(&self, ptr: *const u8) -> Option<Entry> {
let offset = ptr.addr().wrapping_sub(self.private.base.get().addr());
(offset < self.private.span.get()).then(|| self.entry_of(ptr))
}
#[cfg(all(feature = "std", not(loom)))]
#[inline(always)]
pub(crate) fn usable_size(&self, ptr: NonNull<u8>) -> Option<usize> {
let entry = self.entry_in_region(ptr.as_ptr())?;
Some(entry.huge_chunks().map_or_else(|| entry.class().block_size(), |n| n << CHUNK_SHIFT))
}
#[inline(always)]
pub(crate) unsafe fn free_entry(&self, block: *mut Block, entry: Entry) {
let bin = unsafe { &*self.private.bins.as_ptr().byte_add(entry.bin_offset()) };
#[cfg(feature = "metrics")]
bin.frees.add(1);
if entry.owner() != self.private.id.get() && !bin.anywhere.get() {
return unsafe { self.send(block, entry.class(), entry.owner()) };
}
if !Self::push_to(bin, block) {
unsafe { self.free_full(block, entry.class()) };
}
}
#[cold]
#[inline(never)]
unsafe fn free_full(&self, block: *mut Block, class: Class) {
let region = unsafe { self.region() };
unsafe { self.read_mail(region) };
if self.note_miss(class, OVERFLOW) && self.push(class, block) {
return;
}
if self.spill(region, class) && self.push(class, block) {
return;
}
loop {
let keep = usize::from(self.bin(class).capacity.get()) / 2;
unsafe { self.flush_bin(class, keep) };
if self.push(class, block) {
return;
}
}
}
unsafe fn flush_bin(&self, class: Class, keep: usize) {
let region = unsafe { self.region() };
let bin = self.bin(class);
let len = self.bin_len(class);
if len <= keep {
return;
}
let mut out = [ptr::null_mut::<Block>(); FLUSH_BATCH];
let mut len = len;
while len > keep {
let gone = (len - keep).min(FLUSH_BATCH);
let top = bin.top.get();
unsafe {
ptr::copy_nonoverlapping(top.add(len - gone), out.as_mut_ptr(), gone);
ptr::copy(top, top.add(gone), len - gone);
}
bin.top.set(top.wrapping_add(gone));
unsafe { self.give_back(region, class, &out[..gone], false) };
len = self.bin_len(class);
}
}
unsafe fn give_back(
&self,
region: &Region<'_>,
class: Class,
blocks: &[*mut Block],
directly: bool,
) {
let id = self.private.id.get();
let span = class.slab_chunks() << CHUNK_SHIFT;
let mut run: Option<Returns<'_>> = None;
let mut rest = blocks;
while let Some((&block, more)) = rest.split_first() {
rest = more;
if let Some(returns) = &mut run {
if block.addr().wrapping_sub(returns.slab().start().addr()) < span {
unsafe { returns.add(block) };
continue;
}
if let Some(returns) = run.take() {
self.settle(region, returns.finish());
}
}
let owner = self.entry_of(block.cast()).owner();
if owner != id {
let at = blocks.len() - rest.len() - 1;
let given =
unsafe { self.give_away(region, class, &blocks[at..], owner, directly) };
rest = &blocks[at + given..];
continue;
}
let slab =
unsafe { region.slab_of(NonNull::new_unchecked(block.cast()), class).owned() };
let mut returns = Returns::new(slab);
unsafe { returns.add(block) };
run = Some(returns);
}
if let Some(returns) = run {
self.settle(region, returns.finish());
}
}
#[inline(never)]
unsafe fn give_away(
&self,
region: &Region<'_>,
class: Class,
blocks: &[*mut Block],
owner: u32,
directly: bool,
) -> usize {
let mask = !((class.slab_chunks() << CHUNK_SHIFT) - 1);
let mut slab = blocks[0].addr() & mask;
let mut len = 1;
while let Some(&next) = blocks.get(len) {
if next.addr() & mask != slab {
if self.entry_of(next.cast()).owner() != owner {
break;
}
slab = next.addr() & mask;
}
len += 1;
}
let others = &blocks[..len];
if directly {
for &block in others {
unsafe { region.heap_slot(owner).post_block(block) };
}
} else {
unsafe { self.send_run(others, class, owner) };
}
len
}
fn settle(&self, region: &Region<'_>, slab: Owned<'_>) {
if slab.list() == List::Full {
self.move_to(slab, List::Active);
}
if slab.used() == 0 {
self.retire(region, slab);
}
}
unsafe fn free_to_slab(&self, region: &Region<'_>, block: *mut Block, class: Class) {
let slab = unsafe {
let slab = region.slab_of(NonNull::new_unchecked(block.cast()), class).owned();
slab.push(block);
slab
};
self.settle(region, slab);
}
#[cold]
#[inline(never)]
unsafe fn send(&self, block: *mut Block, class: Class, owner: u32) {
if owner & Entry::HUGE_OWNER != 0 {
#[cfg(feature = "metrics")]
self.bin(class).frees.sub(1);
let chunks = (owner & !Entry::HUGE_OWNER) as usize;
return unsafe {
self.free_huge(
NonNull::new_unchecked(block.cast()),
Layout::from_size_align_unchecked(chunks << CHUNK_SHIFT, 16),
)
};
}
count!(self, BlocksSent, 1);
let region = unsafe { self.region() };
let outbox = &self.private.outboxes[owner as usize % OUTBOXES];
let message = unsafe { self.open_outbox(region, outbox, class, owner) };
if message.is_null() {
return unsafe { region.heap_slot(owner).post_block(block) };
}
let count = unsafe {
let count = (*message).count as usize;
(&raw mut (*message).blocks).cast::<*mut Block>().add(count).write(block);
(*message).count = (count + 1) as u32;
count + 1
};
let bytes = outbox.bytes.get() as usize + class.block_size();
outbox.bytes.set(bytes as u32);
if count == MESSAGE_BLOCKS || bytes >= OUTBOX_BYTES {
unsafe { self.post_outbox(region, outbox) };
}
}
unsafe fn send_run(&self, blocks: &[*mut Block], class: Class, owner: u32) {
count!(self, BlocksSent, blocks.len());
let region = unsafe { self.region() };
let size = class.block_size();
let outbox = &self.private.outboxes[owner as usize % OUTBOXES];
let mut rest = blocks;
while !rest.is_empty() {
let message = unsafe { self.open_outbox(region, outbox, class, owner) };
if message.is_null() {
for &block in rest {
unsafe { region.heap_slot(owner).post_block(block) };
}
return;
}
let mut count = unsafe { (*message).count as usize };
let mut bytes = outbox.bytes.get() as usize;
while let Some((&block, more)) = rest.split_first() &&
count < MESSAGE_BLOCKS &&
bytes < OUTBOX_BYTES
{
unsafe {
(&raw mut (*message).blocks).cast::<*mut Block>().add(count).write(block)
};
count += 1;
bytes += size;
rest = more;
}
unsafe { (*message).count = count as u32 };
outbox.bytes.set(bytes as u32);
if count == MESSAGE_BLOCKS || bytes >= OUTBOX_BYTES {
unsafe { self.post_outbox(region, outbox) };
}
}
}
unsafe fn open_outbox(
&self,
region: &Region<'_>,
outbox: &Outbox,
class: Class,
owner: u32,
) -> *mut Message {
if outbox.message.get().is_null() {
unsafe { self.read_mail(region) };
}
let mut message = outbox.message.get();
if !message.is_null() && outbox.dest.get() != owner {
unsafe { self.post_outbox(region, outbox) };
message = outbox.message.get();
}
if message.is_null() {
if class.block_size() >= OUTBOX_BYTES {
return ptr::null_mut();
}
message = self.alloc_message(region);
if message.is_null() {
return message;
}
unsafe { (*message).count = 0 };
outbox.message.set(message);
outbox.bytes.set(0);
}
outbox.dest.set(owner);
unsafe {
if (*message).count == 0 {
(*message).class = class.index() as u32;
} else if (*message).class != class.index() as u32 {
(*message).class = MIXED;
}
}
message
}
unsafe fn post_outbox(&self, region: &Region<'_>, outbox: &Outbox) {
let message = outbox.message.get();
if message.is_null() {
return;
}
let dest = region.heap_slot(outbox.dest.get());
outbox.bytes.set(0);
match unsafe { (*message).count } {
0 => {}
1 => {
unsafe {
(*message).count = 0;
dest.post_block((*message).blocks[0]);
}
}
_ => {
count!(self, MessagesPosted, 1);
outbox.message.set(ptr::null_mut());
unsafe { dest.post(message.cast(), message.cast()) };
}
}
}
fn alloc_message(&self, region: &Region<'_>) -> *mut Message {
if let Some(block) = self.pop(MESSAGE_CLASS) {
return block.cast();
}
if self.fill(region, MESSAGE_CLASS) == 0 {
return ptr::null_mut();
}
self.pop(MESSAGE_CLASS).map_or(ptr::null_mut(), <*mut Block>::cast)
}
unsafe fn read_mail(&self, region: &Region<'_>) -> bool {
if self.private.draining.get() || self.shared.inbox.load(Ordering::Relaxed).is_null() {
return false;
}
self.private.draining.set(true);
unsafe { self.drain_inbox(region) };
self.private.draining.set(false);
true
}
unsafe fn drain_inbox(&self, region: &Region<'_>) {
let mut node = self.shared.inbox.swap(ptr::null_mut(), Ordering::Acquire);
if !node.is_null() {
count!(self, MailReads, 1);
}
while !node.is_null() {
let raw = node.map_addr(|addr| addr & !SINGLE);
let next = unsafe { (*raw).next };
if node.addr() & SINGLE != 0 {
unsafe { self.file(region, raw) };
} else {
let message = raw.cast::<Message>();
unsafe {
let blocks = core::slice::from_raw_parts(
(&raw const (*message).blocks).cast::<*mut Block>(),
(*message).count as usize,
);
match (*message).class {
MIXED => blocks.iter().for_each(|&block| self.file(region, block)),
class => self.file_run(region, Class::from_index(class as usize), blocks),
}
self.free_small(message.cast());
}
}
node = next;
}
}
unsafe fn file_run(&self, region: &Region<'_>, class: Class, blocks: &[*mut Block]) {
count!(self, BlocksFiled, blocks.len());
let bin = self.bin(class);
let room = usize::from(bin.capacity.get()) - self.bin_len(class);
let (kept, rest) = blocks.split_at(room.min(blocks.len()));
let top = bin.top.get().wrapping_sub(kept.len());
unsafe { ptr::copy_nonoverlapping(kept.as_ptr(), top, kept.len()) };
bin.top.set(top);
if !rest.is_empty() {
unsafe { self.give_back(region, class, rest, false) };
}
}
unsafe fn file(&self, region: &Region<'_>, block: *mut Block) {
count!(self, BlocksFiled, 1);
let entry = self.entry_of(block.cast());
debug_assert_eq!(
entry.owner(),
self.private.id.get(),
"a block was sent to the wrong heap"
);
if !self.push(entry.class(), block) {
unsafe { self.free_to_slab(region, block, entry.class()) };
}
}
unsafe fn empty_caches(&self, region: &Region<'_>) {
unsafe { self.drain_inbox(region) };
for index in 0..CLASSES {
unsafe { self.return_spill(region, Class::from_index(index), true) };
}
for kept in &self.private.kept {
let block = kept.replace(Kept::NONE);
if block.chunks != 0 {
region.free_chunks(block.first, block.chunks);
}
}
for outbox in &self.private.outboxes {
unsafe { self.post_outbox(region, outbox) };
let message = outbox.message.replace(ptr::null_mut());
if !message.is_null() {
unsafe { self.give_back(region, MESSAGE_CLASS, &[message.cast()], true) };
}
}
for index in 0..CLASSES {
let class = Class::from_index(index);
let len = self.bin_len(class);
let bin = &self.private.bins[index];
let top = bin.top.get();
bin.top.set(top.wrapping_add(len));
unsafe { self.give_back(region, class, core::slice::from_raw_parts(top, len), true) };
self.set_capacity(class, class.bin_initial());
bin.misses.set(0);
}
self.private.grown.set(0);
}
fn spill(&self, region: &Region<'_>, class: Class) -> bool {
let bin = self.bin(class);
if class == BATCH_CLASS || class == MESSAGE_CLASS || bin.misses.get() & REFILLED == 0 {
return false;
}
let capacity = usize::from(bin.capacity.get());
let room = self.private.grown.get() + capacity * class.block_size() <= GROWTH_BUDGET;
if capacity < class.bin_max() && room {
return false;
}
let len = self.bin_len(class);
let gone = (len - usize::from(bin.capacity.get()) / 2).min(BATCH_BLOCKS);
let bytes = gone * class.block_size();
if gone == 0 {
return false;
}
if self.private.spilled.get() + bytes > SPILL_BUDGET {
bin.misses.set(bin.misses.get() & !REFILLED);
unsafe { self.return_spill(region, class, false) };
return false;
}
let batch = self.alloc_batch(region);
if batch.is_null() {
return false;
}
count!(self, BlocksSpilled, gone);
let lists = self.lists(class);
let top = bin.top.get();
unsafe {
ptr::copy_nonoverlapping(top.add(len - gone), (&raw mut (*batch).blocks).cast(), gone);
ptr::copy(top, top.add(gone), len - gone);
(*batch).count = gone;
(*batch).next = lists.spill.get();
}
bin.top.set(top.wrapping_add(gone));
lists.spill.set(batch);
self.private.spilled.set(self.private.spilled.get() + bytes);
true
}
fn unspill(&self, region: &Region<'_>, class: Class) -> bool {
let lists = self.lists(class);
let batch = lists.spill.get();
if batch.is_null() {
return false;
}
let bin = self.bin(class);
debug_assert_eq!(self.bin_len(class), 0, "a bin takes a batch only when it is empty");
let count = unsafe { (*batch).count };
let take = count.min(usize::from(bin.capacity.get()));
let first = bin.top.get().wrapping_sub(take);
unsafe {
ptr::copy_nonoverlapping(
(&raw const (*batch).blocks).cast::<*mut Block>().add(count - take),
first,
take,
);
}
bin.top.set(first);
count!(self, BlocksUnspilled, take);
lists.unspilled.set(true);
self.private.spilled.set(self.private.spilled.get() - take * class.block_size());
if take == count {
lists.spill.set(unsafe { (*batch).next });
self.free_batch(region, batch);
} else {
unsafe { (*batch).count = count - take };
}
true
}
unsafe fn return_spill(&self, region: &Region<'_>, class: Class, directly: bool) {
let lists = self.lists(class);
loop {
let batch = lists.spill.get();
if batch.is_null() {
return;
}
let blocks = unsafe {
lists.spill.set((*batch).next);
core::slice::from_raw_parts(
(&raw const (*batch).blocks).cast::<*mut Block>(),
(*batch).count,
)
};
self.private
.spilled
.set(self.private.spilled.get() - blocks.len() * class.block_size());
#[cfg(feature = "metrics")]
self.bin(BATCH_CLASS).frees.add(1);
unsafe {
self.give_back(region, class, blocks, directly);
self.give_back(region, BATCH_CLASS, &[batch.cast()], true);
}
}
}
fn alloc_batch(&self, region: &Region<'_>) -> *mut Batch {
if let Some(block) = self.pop(BATCH_CLASS) {
return block.cast();
}
if self.fill(region, BATCH_CLASS) == 0 {
return ptr::null_mut();
}
self.pop(BATCH_CLASS).map_or(ptr::null_mut(), <*mut Block>::cast)
}
fn free_batch(&self, region: &Region<'_>, batch: *mut Batch) {
#[cfg(feature = "metrics")]
self.bin(BATCH_CLASS).frees.add(1);
if !self.push(BATCH_CLASS, batch.cast()) {
unsafe { self.free_to_slab(region, batch.cast(), BATCH_CLASS) };
}
}
fn retire(&self, region: &Region<'_>, slab: Owned<'_>) {
debug_assert_eq!(slab.used(), 0);
let sole_active =
slab.list() == List::Active && slab.prev().is_null() && slab.next().is_null();
if !sole_active {
self.release(region, slab);
}
}
fn release(&self, region: &Region<'_>, slab: Owned<'_>) {
self.unlink(slab);
count!(self, SlabsReleased, 1);
#[cfg(feature = "metrics")]
self.lists(slab.class()).slabs.sub(1);
let first = region.chunk_index(slab.start());
let chunks = slab.class().slab_chunks();
if slab.was_filled() {
self.private.held.set(self.private.held.get().saturating_sub(chunks));
let filled = &self.lists(slab.class()).filled;
filled.set(filled.get().saturating_sub(1));
}
region.free_chunks(first, chunks);
region.purge_if_due();
if region.home(self.slab_part(region, Class::from_index(0))).contains(&(first / 64)) {
self.private.cursor.set(self.private.cursor.get().min(first / 64));
}
}
pub(crate) unsafe fn flush(&self, region: &Region<'_>) {
unsafe { self.empty_caches(region) };
for index in 0..CLASSES {
let class = Class::from_index(index);
for list in [List::Active, List::Full] {
let mut next = self.head(class, list).get();
while let Some(slab) = unsafe { next.as_ref() } {
let slab = unsafe { slab.owned() };
next = slab.next();
if slab.used() == 0 {
self.release(region, slab);
}
}
}
}
}
pub(crate) fn alloc_huge(&self, region: &Region<'_>, chunks: usize, align: usize) -> *mut u8 {
self.alloc_huge_zeroed(region, chunks, align).0
}
fn alloc_huge_zeroed(
&self,
region: &Region<'_>,
chunks: usize,
align: usize,
) -> (*mut u8, bool) {
for kept in &self.private.kept {
let block = kept.get();
if block.chunks == chunks && block.first & (align - 1) == 0 {
kept.set(Kept::NONE);
self.mark_kept_reused(chunks);
count!(self, HugeCacheHits, 1);
self.note_huge_alloc(chunks);
return (region.chunk_ptr(block.first), false);
}
}
let huge = chunks >= HUGE_PAGE_CHUNKS || self.is_big();
let part = region.part(self.private.node.get(), huge);
let Some((first, zeroed)) = region.alloc_chunks_zeroed(chunks, align, 0, part) else {
return (ptr::null_mut(), false);
};
self.note_huge_alloc(chunks);
region.set_huge(first, chunks);
#[cfg(feature = "metrics")]
if zeroed {
count!(self, ZeroedFresh, 1);
}
(region.chunk_ptr(first), zeroed)
}
fn note_huge_alloc(&self, chunks: usize) {
self.private.runs.set(self.private.runs.get() + chunks);
count!(self, HugeAllocs, 1);
count!(self, HugeBytesAllocated, chunks << CHUNK_SHIFT);
}
fn mark_kept_reused(&self, chunks: usize) {
for kept in &self.private.kept {
let block = kept.get();
if block.chunks == chunks {
kept.set(Kept { reused: true, ..block });
}
}
}
fn move_to(&self, slab: Owned<'_>, list: List) {
self.unlink(slab);
match list {
List::Active => self.push_back(slab),
List::Full | List::None => self.push_front(slab, list),
}
}
fn push_front(&self, slab: Owned<'_>, list: List) {
let head = self.head(slab.class(), list);
let old = head.get();
slab.set_prev(ptr::null());
slab.set_next(old);
if let Some(old) = unsafe { old.as_ref() } {
unsafe { old.owned() }.set_prev(slab.slab());
}
head.set(slab.slab());
if list == List::Active && old.is_null() {
self.lists(slab.class()).active_last.set(slab.slab());
}
slab.set_list(list);
}
fn push_back(&self, slab: Owned<'_>) {
let lists = self.lists(slab.class());
let last = lists.active_last.get();
let Some(last) = (unsafe { last.as_ref() }) else {
return self.push_front(slab, List::Active);
};
slab.set_prev(ptr::from_ref(last));
slab.set_next(ptr::null());
unsafe { last.owned() }.set_next(slab.slab());
lists.active_last.set(slab.slab());
slab.set_list(List::Active);
}
fn unlink(&self, slab: Owned<'_>) {
let list = slab.list();
if list == List::None {
return;
}
let (prev, next) = (slab.prev(), slab.next());
match unsafe { prev.as_ref() } {
Some(prev) => unsafe { prev.owned() }.set_next(next),
None => self.head(slab.class(), list).set(next),
}
if let Some(next) = unsafe { next.as_ref() } {
unsafe { next.owned() }.set_prev(prev);
} else if list == List::Active {
self.lists(slab.class()).active_last.set(prev);
}
slab.set_prev(ptr::null());
slab.set_next(ptr::null());
slab.set_list(List::None);
}
#[cfg(any(test, feature = "testing"))]
pub(crate) unsafe fn validate(&self, seen: &mut std::collections::BTreeSet<usize>) {
let region = unsafe { self.region() };
let id = self.private.id.get();
let mut claim = |block: *mut Block, what: &str| {
assert!(seen.insert(block.addr()), "block {block:p} appears twice, last in {what}");
};
let check = |block: *mut Block, what: &str| -> Entry {
assert!(region.contains(block.cast()), "{what} holds a block outside the region");
let entry = self.entry_of(block.cast());
let class = entry.class();
let first = region.chunk_index(block.cast()) & !(class.slab_chunks() - 1);
let offset = block.addr() - region.chunk_ptr(first).addr();
assert!(
offset.is_multiple_of(class.block_size()) &&
offset / class.block_size() < class.blocks_per_slab(),
"{what} holds a pointer that is not a block of its slab"
);
if entry.owner() == id {
let slab =
unsafe { region.slab_of(NonNull::new_unchecked(block.cast()), class).owned() };
assert!(
!slab.is_free(block.cast()),
"{what} holds a block its slab counts as free"
);
}
entry
};
let mut spilled = 0;
for index in 0..CLASSES {
let class = Class::from_index(index);
let lists = &self.private.classes[index];
for (list, head) in [(List::Active, lists.active.get()), (List::Full, lists.full.get())]
{
let mut prev: *const Slab = ptr::null();
let mut current = head;
while let Some(slab) = unsafe { current.as_ref() } {
let owned = unsafe { slab.owned() };
assert_eq!(owned.list(), list, "slab is on the wrong list");
assert_eq!(owned.class(), class, "slab is on the wrong class");
assert!(ptr::eq(owned.prev(), prev), "broken back link");
let entry = self.entry_of(owned.start());
assert_eq!(entry, Entry::new(id, class), "the chunk map disagrees with a slab");
assert_eq!(
owned.is_exhausted(),
list == List::Full,
"a slab with free blocks must be active and an exhausted one full"
);
owned.check();
prev = current;
current = owned.next();
}
if list == List::Active {
assert!(ptr::eq(lists.active_last.get(), prev), "wrong last active slab");
}
}
let bin = &self.private.bins[index];
assert!(
self.bin_len(class) <= usize::from(bin.capacity.get()),
"a bin is over capacity"
);
let mut slot = bin.top.get();
for _ in 0..self.bin_len(class) {
let block = unsafe { *slot };
let entry = check(block, "a bin");
assert_eq!(entry.class(), class, "a bin holds a block of another class");
assert!(
entry.owner() == id || bin.anywhere.get(),
"a bin holds another heap's block of a class that must go home"
);
claim(block, "a bin");
slot = slot.wrapping_add(1);
}
let mut batch = lists.spill.get();
while !batch.is_null() {
assert_eq!(check(batch.cast(), "a spill").class(), BATCH_CLASS);
claim(batch.cast(), "a spill");
let blocks = unsafe { &(&(*batch).blocks)[..(*batch).count] };
assert!(!blocks.is_empty() && class != BATCH_CLASS, "a spilled batch is wrong");
for &block in blocks {
let entry = check(block, "a spill");
assert_eq!(entry.class(), class, "a spill holds a block of another class");
assert!(
entry.owner() == id || bin.anywhere.get(),
"a spill holds another heap's block of a class that must go home"
);
claim(block, "a spill");
spilled += class.block_size();
}
batch = unsafe { (*batch).next };
}
}
assert_eq!(spilled, self.private.spilled.get(), "the spill budget disagrees");
for outbox in &self.private.outboxes {
let message = outbox.message.get();
if message.is_null() {
continue;
}
assert_eq!(check(message.cast(), "an outbox").class(), MESSAGE_CLASS);
claim(message.cast(), "an outbox");
let blocks = unsafe { &(&(*message).blocks)[..(*message).count as usize] };
assert!(blocks.len() < MESSAGE_BLOCKS, "a full message was not posted");
let class = unsafe { (*message).class };
assert!(
blocks.is_empty() ||
class == MIXED ||
blocks.iter().all(
|&block| self.entry_of(block.cast()).class().index() == class as usize
),
"a message of one class holds a block of another"
);
for &block in blocks {
let entry = check(block, "an outbox");
assert_eq!(
entry.owner(),
outbox.dest.get(),
"an outbox holds a block for another heap"
);
assert_ne!(entry.owner(), id, "an outbox holds a block of this heap");
claim(block, "an outbox");
}
}
let mut node = self.shared.inbox.load(Ordering::Acquire);
while !node.is_null() {
let raw = node.map_addr(|addr| addr & !SINGLE);
if node.addr() & SINGLE != 0 {
assert_eq!(
check(raw, "the inbox").owner(),
id,
"a block was sent to the wrong heap"
);
claim(raw, "the inbox");
} else {
let message = raw.cast::<Message>();
claim(raw, "the inbox");
for &block in unsafe { &(&(*message).blocks)[..(*message).count as usize] } {
assert_eq!(check(block, "the inbox").owner(), id, "a message went astray");
claim(block, "the inbox");
}
}
node = unsafe { (*raw).next };
}
}
}
#[derive(Debug)]
pub struct Heap<'r> {
region: &'r Region<'r>,
data: &'r HeapData,
_not_sync: PhantomData<Cell<()>>,
}
unsafe impl Send for Heap<'_> {}
impl<'r> Heap<'r> {
pub(crate) const fn new(region: &'r Region<'r>, data: &'r HeapData) -> Self {
Self { region, data, _not_sync: PhantomData }
}
pub const fn region(&self) -> &'r Region<'r> {
self.region
}
#[inline]
pub fn alloc(&self, layout: Layout) -> Option<NonNull<u8>> {
NonNull::new(unsafe { self.data.alloc(layout) })
}
pub fn alloc_zeroed(&self, layout: Layout) -> Option<NonNull<u8>> {
NonNull::new(unsafe { self.data.alloc_zeroed(layout) })
}
#[inline]
pub unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { self.data.dealloc(ptr, layout) };
}
pub unsafe fn free_unsized(&self, ptr: NonNull<u8>) {
unsafe { self.data.free_unsized(ptr) };
}
pub unsafe fn realloc(
&self,
ptr: NonNull<u8>,
old: Layout,
new_size: usize,
) -> Option<NonNull<u8>> {
NonNull::new(unsafe { self.data.realloc(ptr, old, new_size) })
}
#[cfg(any(test, feature = "testing"))]
pub fn settle_on(&self, node: usize) {
self.data.settle_on(self.region, node);
}
#[cfg(any(test, feature = "testing"))]
pub fn validate(&self) {
self.validate_into(&mut std::collections::BTreeSet::new());
}
#[cfg(any(test, feature = "testing"))]
pub(crate) fn validate_into(&self, seen: &mut std::collections::BTreeSet<usize>) {
unsafe { self.data.validate(seen) };
}
#[cfg(all(feature = "std", not(loom)))]
pub(crate) const fn leak(self) -> &'r HeapData {
let data = self.data;
core::mem::forget(self);
data
}
pub fn flush(&self) {
unsafe { self.data.flush(self.region) };
}
}
impl Drop for Heap<'_> {
fn drop(&mut self) {
unsafe { self.data.give_up() };
}
}
#[cfg(all(test, not(loom)))]
mod test {
use super::*;
use crate::{
MAX_ALIGN,
chunks::CHUNK_SIZE,
testing::{Harness, Rng, TestRegion, iterations, random_traffic},
};
use core::{
alloc::Layout,
mem::{MaybeUninit, align_of, offset_of, size_of},
ptr::NonNull,
slice,
};
use std::vec::Vec;
fn layout(size: usize, align: usize) -> Layout {
Layout::from_size_align(size, align).unwrap()
}
fn used(region: &Region<'_>) -> usize {
let stats = region.stats();
stats.capacity - stats.free
}
fn alloc_many(heap: &Heap<'_>, layout: Layout, count: usize) -> Vec<NonNull<u8>> {
(0..count).map(|_| heap.alloc(layout).expect("region has room")).collect()
}
fn free_all(heap: &Heap<'_>, layout: Layout, blocks: Vec<NonNull<u8>>) {
for block in blocks {
unsafe { heap.dealloc(block, layout) };
}
}
fn has_mail(heap: &Heap<'_>) -> bool {
!heap.data.shared.inbox.load(Ordering::Relaxed).is_null()
}
const HOMEBOUND: usize = 100;
const ANYWHERE: usize = 256;
#[test]
fn the_test_sizes_fall_on_both_sides_of_the_reuse_rule() {
assert!(!Class::for_size(HOMEBOUND).reusable_anywhere());
assert!(Class::for_size(ANYWHERE).reusable_anywhere());
assert!(reusable_anywhere(MESSAGE_CLASS), "messages are recycled by whoever reads them");
}
#[test]
fn a_heap_slot_keeps_what_other_threads_write_on_its_own_line() {
let line = align_of::<CacheLine>();
assert_eq!(align_of::<HeapData>(), line);
assert_eq!(offset_of!(HeapData, shared) % line, 0);
assert_eq!(offset_of!(HeapData, private) % line, 0);
assert_ne!(offset_of!(HeapData, shared), offset_of!(HeapData, private));
assert_eq!(size_of::<HeapData>() % line, 0);
}
#[test]
fn blocks_are_distinct_aligned_and_keep_their_contents() {
let test = TestRegion::new(128, 1);
let region = test.region();
let mut harness = Harness::new(®ion, 1);
let mut rng = Rng::new(1);
for _ in 0..iterations(2_000) {
harness.alloc(0, rng.between(1, 3000), 1 << rng.below(8));
}
harness.finish();
}
#[test]
fn a_freed_block_is_the_next_one_handed_out() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
for size in [16, HOMEBOUND, ANYWHERE, 5000, 100_000] {
let layout = layout(size, 8);
let block = heap.alloc(layout).unwrap();
unsafe { heap.dealloc(block, layout) };
assert_eq!(heap.alloc(layout), Some(block), "{size}");
}
}
#[test]
fn allocation_and_free_in_a_loop_never_grows_the_region() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let layout = layout(200, 8);
let block = heap.alloc(layout).unwrap();
unsafe { heap.dealloc(block, layout) };
let baseline = used(®ion);
for _ in 0..iterations(10_000) {
let block = heap.alloc(layout).unwrap();
unsafe { heap.dealloc(block, layout) };
}
assert_eq!(used(®ion), baseline);
}
#[test]
fn empty_slabs_go_back_except_one_and_flush_returns_the_rest() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let layout = layout(64, 8);
let blocks = alloc_many(&heap, layout, 3000);
assert_eq!(used(®ion), 3 * CHUNK_SIZE);
free_all(&heap, layout, blocks);
assert!(used(®ion) <= 2 * CHUNK_SIZE, "empty slabs should be released");
heap.validate();
heap.flush();
assert_eq!(used(®ion), 0);
}
const SPILL_SIZE: usize = if cfg!(miri) { 2048 } else { 64 };
#[test]
fn a_burst_bigger_than_the_bin_spills_and_the_next_burst_takes_it_back() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let layout = layout(SPILL_SIZE, 8);
let burst = 4 * Class::for_size(SPILL_SIZE).bin_max();
for _ in 0..8 {
let blocks = alloc_many(&heap, layout, burst);
free_all(&heap, layout, blocks);
}
heap.validate();
assert!(heap.data.private.spilled.get() > 0, "an overflowing bin spills");
let slabs = used(®ion);
let blocks = alloc_many(&heap, layout, burst);
assert_eq!(used(®ion), slabs, "the next burst reuses the last one's blocks");
heap.validate();
free_all(&heap, layout, blocks);
heap.flush();
assert_eq!(heap.data.private.spilled.get(), 0);
assert_eq!(used(®ion), 0, "a flush returns spilled blocks to their slabs");
}
#[test]
fn a_burst_bigger_than_the_spill_budget_keeps_no_batches() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let layout = layout(SPILL_SIZE, 8);
let class = Class::for_size(SPILL_SIZE);
for _ in 0..8 {
let blocks = alloc_many(&heap, layout, 4 * class.bin_max());
free_all(&heap, layout, blocks);
}
assert!(!heap.data.lists(class).spill.get().is_null(), "bursts that fit spill");
let burst = 2 * SPILL_BUDGET / class.block_size();
let blocks = alloc_many(&heap, layout, burst);
free_all(&heap, layout, blocks);
heap.validate();
assert!(heap.data.lists(class).spill.get().is_null(), "the burst outgrew the batches");
assert_eq!(heap.data.private.spilled.get(), 0);
heap.flush();
assert_eq!(used(®ion), 0);
}
#[test]
fn spilled_batches_that_no_refill_takes_go_back_at_maintenance() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let (layout, other) = (layout(SPILL_SIZE, 8), layout(1024, 8));
let class = Class::for_size(SPILL_SIZE);
for _ in 0..8 {
let blocks = alloc_many(&heap, layout, 4 * class.bin_max());
free_all(&heap, layout, blocks);
}
assert!(!heap.data.lists(class).spill.get().is_null());
for _ in 0..16 {
if heap.data.lists(class).spill.get().is_null() {
break;
}
let blocks = alloc_many(&heap, other, 16 * MAINTENANCE_INTERVAL as usize);
free_all(&heap, other, blocks);
}
heap.validate();
assert!(heap.data.lists(class).spill.get().is_null(), "idle batches go back");
}
#[test]
fn a_heap_that_only_frees_a_class_never_spills_it() {
let test = TestRegion::new(128, 2);
let region = test.region();
let (owner, freer) = (region.heap().unwrap(), region.heap().unwrap());
let size = if cfg!(miri) { ANYWHERE } else { 64 };
let layout = layout(size, 8);
for _ in 0..if cfg!(miri) { 2 } else { 8 } {
let blocks = alloc_many(&owner, layout, 4 * Class::for_size(size).bin_max());
free_all(&freer, layout, blocks);
}
freer.validate();
assert_eq!(freer.data.private.spilled.get(), 0, "no refill would take a spill");
freer.flush();
owner.flush();
}
#[test]
fn a_full_bin_gives_back_its_older_half() {
let test = TestRegion::new(16, 1);
let region = test.region();
let heap = region.heap().unwrap();
let class = Class::for_size(ANYWHERE);
let layout = layout(ANYWHERE, 8);
let blocks = alloc_many(&heap, layout, 4 * class.bin_max());
let newest = *blocks.last().unwrap();
free_all(&heap, layout, blocks);
let capacity = usize::from(heap.data.private.bins[class.index()].capacity.get());
assert!(capacity > class.bin_initial(), "a bin that runs dry and overflows grows");
let len = heap.data.bin_len(class);
assert!(len > capacity / 2 && len <= capacity, "{len} blocks are left in the bin");
assert_eq!(heap.alloc(layout), Some(newest), "the newest blocks stay");
heap.validate();
}
#[test]
fn blocks_aligned_past_a_chunk_are_runs_that_start_on_their_alignment() {
let test = TestRegion::new(320, 1);
let region = test.region();
let heap = region.heap().unwrap();
let loose = layout(2 * CHUNK_SIZE, 8);
let kept = heap.alloc(loose).unwrap();
assert!(!kept.as_ptr().addr().is_multiple_of(2 << 20));
unsafe { heap.dealloc(kept, loose) };
for align in [2 * CHUNK_SIZE, 2 << 20, MAX_ALIGN] {
for size in [8, CHUNK_SIZE, 2 * CHUNK_SIZE] {
let layout = layout(size, align);
let block = heap.alloc(layout).unwrap();
assert!(block.as_ptr().addr().is_multiple_of(align), "{size} aligned to {align}");
unsafe { block.as_ptr().write_bytes(1, size) };
let grown_size = size + 3 * CHUNK_SIZE;
let grown = unsafe { heap.realloc(block, layout, grown_size) }.unwrap();
assert!(grown.as_ptr().addr().is_multiple_of(align), "a resize kept the alignment");
for at in [0, size / 2, size - 1] {
assert_eq!(unsafe { grown.as_ptr().add(at).read() }, 1, "byte {at} moved");
}
unsafe { heap.dealloc(grown, Layout::from_size_align(grown_size, align).unwrap()) };
}
let zeroed = heap.alloc_zeroed(layout(100, align)).unwrap();
assert!(zeroed.as_ptr().addr().is_multiple_of(align));
assert!(unsafe { slice::from_raw_parts(zeroed.as_ptr(), 100) }.iter().all(|&b| b == 0));
unsafe { heap.dealloc(zeroed, layout(100, align)) };
}
let block = heap.alloc(layout(100, 2 << 20)).unwrap();
assert!(heap.data.usable_size(block).unwrap() > crate::MAX_SMALL);
unsafe { heap.free_unsized(block) };
assert_eq!(heap.alloc(layout(8, MAX_ALIGN * 2)), None, "the limit is one bitmap word");
heap.validate();
heap.flush();
assert_eq!(used(®ion), 0);
}
#[test]
fn huge_allocations_span_chunks_and_release_them() {
let test = TestRegion::new(160, 1);
let region = test.region();
let mut harness = Harness::new(®ion, 1);
assert!(harness.alloc(0, 576 << 10, 1));
assert!(harness.alloc(0, 5 << 20, 4096));
assert_eq!(used(®ion), (9 + 80) * CHUNK_SIZE);
harness.finish();
}
#[test]
fn blocks_freed_by_another_heap_go_home_and_are_reused_by_the_owner() {
let test = TestRegion::new(128, 2);
let region = test.region();
let (owner, other) = (region.heap().unwrap(), region.heap().unwrap());
let layout = layout(HOMEBOUND, 8);
let blocks = alloc_many(&owner, layout, 500);
free_all(&other, layout, blocks);
other.flush();
owner.validate();
other.validate();
let baseline = used(®ion);
let again = alloc_many(&owner, layout, 500);
assert_eq!(used(®ion), baseline, "the owner must recycle what the other heap freed");
free_all(&owner, layout, again);
}
#[test]
fn a_heap_that_only_frees_takes_back_its_messages() {
let test = TestRegion::new(256, 2);
let region = test.region();
let (producer, consumer) = (region.heap().unwrap(), region.heap().unwrap());
let layout = layout(HOMEBOUND, 8);
for _ in 0..iterations(400) {
let blocks = alloc_many(&producer, layout, 2000);
free_all(&consumer, layout, blocks);
}
producer.validate();
consumer.validate();
assert!(used(®ion) < 32 * CHUNK_SIZE, "{} chunks in use", used(®ion) / CHUNK_SIZE);
}
#[test]
fn a_heap_reuses_blocks_of_others_only_where_they_share_no_line() {
let test = TestRegion::new(16, 2);
let region = test.region();
let (owner, other) = (region.heap().unwrap(), region.heap().unwrap());
for (size, reused) in [(ANYWHERE, true), (HOMEBOUND, false)] {
let layout = layout(size, 8);
let block = owner.alloc(layout).unwrap();
unsafe { other.dealloc(block, layout) };
let next = other.alloc(layout).unwrap();
assert_eq!(next == block, reused, "{size}");
owner.validate();
other.validate();
}
}
#[test]
fn an_outbox_is_posted_when_its_message_fills_or_on_flush() {
let test = TestRegion::new(16, 2);
let region = test.region();
let (owner, other) = (region.heap().unwrap(), region.heap().unwrap());
let layout = layout(HOMEBOUND, 8);
let blocks = alloc_many(&owner, layout, MESSAGE_BLOCKS + 1);
let mut blocks = blocks.into_iter();
free_all(&other, layout, blocks.by_ref().take(MESSAGE_BLOCKS - 1).collect());
assert!(!has_mail(&owner), "a message is held back until it fills");
free_all(&other, layout, blocks.by_ref().take(1).collect());
assert!(has_mail(&owner), "a full message is posted");
owner.validate();
other.validate();
free_all(&other, layout, blocks.collect());
other.flush();
let node = owner.data.shared.inbox.load(Ordering::Relaxed);
assert_eq!(node.addr() & SINGLE, SINGLE, "one block is sent on its own");
owner.flush();
other.flush();
assert_eq!(used(®ion), 0, "everything came home and was released");
}
#[test]
fn a_message_for_another_heap_posts_what_the_outbox_holds() {
let test = TestRegion::new(16, 3);
let region = test.region();
let heaps = [region.heap().unwrap(), region.heap().unwrap(), region.heap().unwrap()];
let layout = layout(HOMEBOUND, 8);
let a = heaps[0].alloc(layout).unwrap();
let b = heaps[1].alloc(layout).unwrap();
unsafe {
heaps[2].dealloc(a, layout);
heaps[2].dealloc(b, layout);
}
assert!(!has_mail(&heaps[0]) && !has_mail(&heaps[1]), "different outboxes hold them");
for heap in &heaps {
heap.validate();
}
heaps[2].flush();
assert!(has_mail(&heaps[0]) && has_mail(&heaps[1]));
}
#[test]
fn formatting_a_region_does_not_read_state_owned_by_a_heap() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
std::thread::scope(|scope| {
scope.spawn(move || {
heap.alloc(layout(8, 8)).unwrap();
});
let _ = std::format!("{region:?}");
});
}
#[test]
#[should_panic(expected = "at least one chunk")]
fn a_test_region_needs_a_chunk() {
let _ = TestRegion::new(0, 1);
}
#[test]
fn an_exhausted_region_fails_cleanly_and_recovers() {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
let layout = layout(8192, 8);
let mut blocks = Vec::new();
while let Some(block) = heap.alloc(layout) {
blocks.push(block);
}
assert_eq!(blocks.len(), 64);
assert_eq!(region.stats().free, 0);
assert!(heap.alloc(layout).is_none());
free_all(&heap, layout, blocks.drain(..8).collect());
assert!(heap.alloc(layout).is_some());
}
#[test]
fn a_failed_allocation_reclaims_this_heaps_empty_slabs_and_retries() {
let test = TestRegion::new(9, 1);
let region = test.region();
let heap = region.heap().unwrap();
let small = layout(16, 8);
let block = heap.alloc(small).unwrap();
unsafe { heap.dealloc(block, small) };
assert_eq!(used(®ion), CHUNK_SIZE, "the empty slab is retained");
let huge = layout(9 * CHUNK_SIZE, 1);
assert!(heap.alloc(huge).is_some(), "retained slabs must not block a large allocation");
}
#[test]
fn realloc_stays_in_place_within_a_class_and_copies_across_classes() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let old = layout(100, 8);
let block = heap.alloc(old).unwrap();
unsafe { block.as_ptr().write_bytes(0xAB, 100) };
let same = unsafe { heap.realloc(block, old, 104) }.unwrap();
assert_eq!(same, block, "100 and 104 bytes share a size class");
let grown = unsafe { heap.realloc(same, layout(104, 8), 5000) }.unwrap();
assert_ne!(grown, block);
let copied = unsafe { core::slice::from_raw_parts(grown.as_ptr(), 100) };
assert!(copied.iter().all(|&byte| byte == 0xAB));
unsafe { heap.dealloc(grown, layout(5000, 8)) };
}
#[test]
fn a_block_that_shrinks_by_at_most_half_keeps_its_place_and_its_class() {
let test = TestRegion::new(16, 1);
let region = test.region();
let heap = region.heap().unwrap();
let block = heap.alloc(layout(1000, 8)).unwrap();
let same = unsafe { heap.realloc(block, layout(1000, 8), 600) }.unwrap();
assert_eq!(same, block, "600 bytes waste less than half of a 1 KiB block");
let moved = unsafe { heap.realloc(same, layout(600, 8), 300) }.unwrap();
assert_ne!(moved, block, "300 bytes would waste more than half");
assert_eq!(heap.alloc(layout(1024, 8)), Some(block));
heap.validate();
}
#[test]
fn a_freed_huge_block_is_kept_for_the_next_request_of_its_size() {
let test = TestRegion::new(320, 1);
let region = test.region();
let heap = region.heap().unwrap();
let big = layout(1 << 20, 8);
let block = heap.alloc(big).unwrap();
unsafe { heap.dealloc(block, big) };
assert_eq!(used(®ion), 16 * CHUNK_SIZE, "the block is kept, still claimed");
assert_eq!(heap.alloc(big), Some(block), "and handed out again");
unsafe { heap.dealloc(block, big) };
let other = layout(2 << 20, 8);
let second = heap.alloc(other).unwrap();
assert_ne!(second, block, "a request of another size does not take it");
unsafe { heap.dealloc(second, other) };
let giant = layout(12 << 20, 8);
let third = heap.alloc(giant).unwrap();
unsafe { heap.dealloc(third, giant) };
assert_eq!(used(®ion), 48 * CHUNK_SIZE, "a block over 8 MiB is not kept");
heap.flush();
assert_eq!(used(®ion), 0, "a flush gives kept blocks back");
}
#[test]
fn huge_blocks_shrink_in_place_and_grow_into_free_chunks() {
let test = TestRegion::new(64, 1);
let region = test.region();
let heap = region.heap().unwrap();
let big = layout(20 * CHUNK_SIZE, 8);
let block = heap.alloc(big).unwrap();
assert_eq!(used(®ion), 20 * CHUNK_SIZE);
let shrunk = unsafe { heap.realloc(block, big, 12 * CHUNK_SIZE) }.unwrap();
assert_eq!((shrunk, used(®ion)), (block, 12 * CHUNK_SIZE), "the tail goes back");
let grown = unsafe { heap.realloc(shrunk, layout(12 * CHUNK_SIZE, 8), 18 * CHUNK_SIZE) };
assert_eq!(grown, Some(block), "the chunks after the block were free");
assert_eq!(used(®ion), 18 * CHUNK_SIZE);
unsafe { heap.dealloc(block, layout(18 * CHUNK_SIZE, 8)) };
heap.flush();
assert_eq!(used(®ion), 0);
}
#[test]
fn heaps_take_chunks_from_their_own_node_first() {
let test = TestRegion::with_nodes(256, 2, 2);
let region = test.region();
let (near, far) = (region.heap().unwrap(), region.heap().unwrap());
near.settle_on(0);
far.settle_on(1);
let small = layout(8192, 8);
let chunk = |block: NonNull<u8>| region.chunk_index(block.as_ptr());
let mine = alloc_many(&near, small, 8 * 100);
assert!(mine.iter().all(|&block| chunk(block) < 128), "node 0 owns chunks 0 to 127");
let theirs = alloc_many(&far, small, 8 * 100);
assert!(theirs.iter().all(|&block| chunk(block) >= 128), "node 1 owns chunks 128 up");
let more = alloc_many(&near, small, 8 * 40);
assert!(more.iter().any(|&block| chunk(block) >= 128), "a full part borrows from others");
let huge = far.alloc(layout(9 * CHUNK_SIZE, 8)).unwrap();
assert!(chunk(huge) >= 128, "huge blocks come from the node's part too");
near.validate();
far.validate();
}
#[test]
fn frees_without_a_layout_find_small_and_huge_blocks_and_skip_others() {
let test = TestRegion::new(256, 2);
let region = test.region();
let (heap, other) = (region.heap().unwrap(), region.heap().unwrap());
let small = alloc_many(&heap, layout(48, 8), 100);
let theirs = alloc_many(&other, layout(4000, 8), 10);
let huge = heap.alloc(layout(9 * CHUNK_SIZE + 1, 8)).unwrap();
let mut outside = 0_u64;
unsafe {
for &block in small.iter().chain(&theirs) {
heap.free_unsized(block);
}
heap.free_unsized(huge);
heap.free_unsized(NonNull::from(&mut outside).cast());
}
heap.flush();
other.flush();
heap.flush();
heap.validate();
other.validate();
assert_eq!(used(®ion), 0, "every block went back to its slab or the chunk allocator");
}
#[test]
fn shrinking_a_bin_that_takes_in_mail_while_it_shrinks_keeps_it_within_capacity() {
let test = TestRegion::new(256, 2);
let region = test.region();
let (heap, other) = (region.heap().unwrap(), region.heap().unwrap());
let class = Class::for_size(ANYWHERE);
assert!(class.reusable_anywhere(), "the bin keeps the other heap's blocks");
let layout = layout(class.block_size(), 8);
let max = class.bin_max();
heap.data.set_capacity(class, max);
heap.data.private.grown.set((max - class.bin_initial()) * class.block_size());
let mine = alloc_many(&heap, layout, max);
free_all(&other, layout, mine);
other.flush();
assert!(has_mail(&heap));
let theirs = alloc_many(&other, layout, max);
free_all(&heap, layout, theirs);
heap.data.bin(class).misses.set(0);
heap.data.private.refills.set(MAINTENANCE_INTERVAL - 1);
unsafe { heap.data.maintain(®ion) };
let capacity = usize::from(heap.data.bin(class).capacity.get());
assert!(capacity < max, "the idle bin shrank");
assert!(heap.data.bin_len(class) <= capacity);
heap.validate();
other.validate();
heap.flush();
other.flush();
heap.flush();
assert_eq!(used(®ion), 0);
}
#[test]
fn zeroed_requests_read_as_zeros_whether_memory_is_fresh_reused_or_cached() {
let test = TestRegion::new(256, 1);
let region = test.region();
let heap = region.heap().unwrap();
let check = |block: NonNull<u8>, size: usize| {
let bytes = unsafe { core::slice::from_raw_parts(block.as_ptr(), size) };
assert!(bytes.iter().all(|&byte| byte == 0), "a zeroed block of {size} has data");
};
let sizes: &[usize] = if cfg!(miri) {
&[24, 4096]
} else {
&[24, 2000, 4096, 20 << 10, 9 * CHUNK_SIZE + 5, 3 << 20]
};
for &size in sizes {
let layout = layout(size, 8);
for _ in 0..3 {
let count = if size > CHUNK_SIZE { 3 } else { 40 };
let blocks: Vec<_> =
(0..count).map(|_| heap.alloc_zeroed(layout).unwrap()).collect();
for &block in &blocks {
check(block, size);
unsafe { block.as_ptr().write_bytes(0xa5, size) };
}
free_all(&heap, layout, blocks);
if size > 4096 {
heap.flush();
}
}
}
heap.flush();
heap.validate();
assert_eq!(used(®ion), 0);
}
#[test]
fn blocks_are_as_aligned_as_their_layouts_ask() {
let test = TestRegion::new(64, 1);
let region = test.region();
let heap = region.heap().unwrap();
for size in [8, 24, 40, 56, 120, 136] {
for align in [8, 16] {
let blocks = alloc_many(&heap, layout(size, align), 50);
assert!(blocks.iter().all(|block| block.as_ptr().addr() % align == 0));
free_all(&heap, layout(size, align), blocks);
}
}
}
#[test]
fn big_heaps_and_big_blocks_take_chunks_from_the_huge_page_zone() {
let test = TestRegion::new(256, 2).with_huge_zone();
let region = test.region();
let (big, small) = (region.heap().unwrap(), region.heap().unwrap());
let chunk = |block: NonNull<u8>| region.chunk_index(block.as_ptr());
let blocks = layout(8192, 8);
let first = alloc_many(&big, blocks, 8 * (HUGE_ZONE_CHUNKS - 4));
assert!(first.iter().all(|&block| chunk(block) < 128), "a small heap uses small pages");
let later = alloc_many(&big, blocks, 8 * 16);
assert!(chunk(*later.last().unwrap()) >= 128, "a big heap moves to the huge page zone");
let sparse = big.alloc(layout(20 << 10, 8)).unwrap();
assert!(chunk(sparse) < 128, "a slab of several chunks of a big heap uses small pages");
let run = big.alloc(layout(9 * CHUNK_SIZE, 8)).unwrap();
assert!(chunk(run) >= 128, "a block of whole chunks of a big heap uses huge pages");
let medium = small.alloc(layout(9 * CHUNK_SIZE, 8)).unwrap();
assert!(chunk(medium) < 128, "and one of a small heap does not");
let large = small.alloc(layout(HUGE_PAGE_CHUNKS * CHUNK_SIZE, 8)).unwrap();
assert!(chunk(large) >= 128, "a block of a huge page or more uses huge pages");
let next = small.alloc(layout(9 * CHUNK_SIZE, 8)).unwrap();
assert!(chunk(next) >= 128, "a heap is big once it holds big blocks too");
for block in first.into_iter().chain(later) {
unsafe { big.dealloc(block, blocks) };
}
unsafe {
big.dealloc(sparse, layout(20 << 10, 8));
big.dealloc(run, layout(9 * CHUNK_SIZE, 8));
}
big.flush();
let again = big.alloc(blocks).unwrap();
assert!(chunk(again) < 128, "a heap that shrank to a quarter goes back to small pages");
big.validate();
small.validate();
}
#[test]
fn a_dropped_heaps_slot_and_slabs_pass_to_the_next_claimant() {
let test = TestRegion::new(128, 2);
let region = test.region();
let (first, second) = (region.heap().unwrap(), region.heap().unwrap());
assert!(region.heap().is_none(), "both slots are taken");
assert_eq!(region.stats().heaps_in_use, 2);
let layout = layout(48, 8);
let blocks = alloc_many(&first, layout, 100);
drop(first);
let successor = region.heap().unwrap();
free_all(&successor, layout, blocks);
successor.validate();
drop((second, successor));
assert_eq!(region.stats().heaps_in_use, 0);
}
#[test]
fn spare_heaps_serve_one_borrower_at_a_time_keep_their_slabs_and_are_trimmed() {
let test = TestRegion::new(128, 1).with_spare_heaps(2);
let region = test.region();
let bound = region.heap().unwrap();
assert!(region.heap().is_none(), "spare heaps are never handed out");
let (first, data) = region.borrow_spare(0);
let (second, other) = region.borrow_spare(0);
assert_eq!((first, second), (0, 1), "a borrowed spare is passed over");
other.release_claim();
let layout = layout(48, 8);
let block = NonNull::new(unsafe { data.alloc(layout) }).unwrap();
data.release_claim();
let (again, data) = region.borrow_spare(first);
assert_eq!(again, first, "a free spare is taken where the hint says");
let next = NonNull::new(unsafe { data.alloc(layout) }).unwrap();
data.release_claim();
let chunk = |block: NonNull<u8>| block.as_ptr().addr() / CHUNK_SIZE;
assert_eq!(chunk(block), chunk(next), "the spare kept its slab for the next borrower");
assert_eq!(region.stats().heaps_in_use, 1, "spare heaps are not heaps in use");
unsafe {
bound.dealloc(block, layout);
region.dealloc(next, layout);
}
bound.flush();
drop(bound);
region.trim();
assert_eq!(used(®ion), 0, "the spare gave its slab back");
}
#[test]
fn a_thread_without_a_heap_can_still_free() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let (small, huge) = (layout(300, 8), layout(2 << 20, 1));
let blocks = alloc_many(&heap, small, 50);
let big = heap.alloc(huge).unwrap();
for block in blocks {
unsafe { region.dealloc(block, small) };
}
unsafe { region.dealloc(big, huge) };
heap.validate();
heap.flush();
assert_eq!(used(®ion), 0);
}
#[test]
fn trimming_empties_idle_heaps() {
let test = TestRegion::new(128, 1);
let region = test.region();
let heap = region.heap().unwrap();
let layout = layout(1000, 8);
let blocks = alloc_many(&heap, layout, 200);
free_all(&heap, layout, blocks);
let held = used(®ion);
assert!(held > 0);
region.trim();
assert_eq!(used(®ion), held);
drop(heap);
region.trim();
assert_eq!(used(®ion), 0);
}
#[test]
fn threads_that_start_together_each_get_a_heap() {
const THREADS: usize = 16;
for _ in 0..iterations(300) {
let test = TestRegion::new(1, THREADS);
let region = test.region();
let barrier = std::sync::Barrier::new(THREADS);
let claimed: usize = std::thread::scope(|scope| {
let handles: Vec<_> = (0..THREADS)
.map(|_| {
scope.spawn(|| {
barrier.wait();
let heap = region.heap();
barrier.wait();
heap.is_some()
})
})
.collect();
handles.into_iter().map(|handle| usize::from(handle.join().unwrap())).sum()
});
assert_eq!(claimed, THREADS, "a claim failed with free slots");
}
}
#[test]
fn threads_that_free_each_others_blocks_lose_nothing() {
const THREADS: usize = 4;
let test = TestRegion::new(256, THREADS);
let region = test.region();
let rounds = iterations(200);
let (senders, receivers): (Vec<_>, Vec<_>) =
(0..THREADS).map(|_| std::sync::mpsc::channel::<Vec<(usize, usize)>>()).unzip();
std::thread::scope(|scope| {
for (id, receiver) in receivers.into_iter().enumerate() {
let next = senders[(id + 1) % THREADS].clone();
let region = ®ion;
scope.spawn(move || {
let heap = region.heap().unwrap();
let mut rng = Rng::new(id as u64);
for _ in 0..rounds {
let batch: Vec<_> = (0..64)
.map(|_| {
let size = rng.between(1, 2000);
let block = heap.alloc(layout(size, 8)).unwrap();
unsafe { block.as_ptr().write_bytes(id as u8, size) };
(block.as_ptr().addr(), size)
})
.collect();
next.send(batch).unwrap();
let batch = receiver.recv().unwrap();
for (addr, size) in batch {
let block = region.chunk_ptr(0).with_addr(addr);
unsafe { heap.dealloc(NonNull::new(block).unwrap(), layout(size, 8)) };
}
}
heap
});
}
drop(senders);
});
region.trim();
assert_eq!(used(®ion), 0, "every block came home");
}
#[test]
fn oversized_alignment_is_refused() {
let test = TestRegion::new(16, 1);
let region = test.region();
let heap = region.heap().unwrap();
assert!(heap.alloc(layout(8, 2 * MAX_ALIGN)).is_none());
assert!(heap.alloc(layout(8, MAX_ALIGN)).is_some());
}
#[test]
fn an_all_zero_slot_is_an_unclaimed_heap() {
let data: HeapData = unsafe { MaybeUninit::zeroed().assume_init() };
let test = TestRegion::new(4, 1);
let region = test.region();
assert!(!data.is_claimed());
assert!(data.claim(0, ®ion));
assert!(!data.claim(0, ®ion), "a claimed slot cannot be claimed again");
data.release_claim();
assert!(data.claim(0, ®ion));
}
#[test]
fn random_traffic_across_three_heaps_keeps_every_invariant() {
for seed in 0..iterations(20) as u64 {
let test = TestRegion::new(160, 3);
random_traffic(&test.region(), seed, iterations(4_000));
}
}
}
#[cfg(all(test, loom))]
mod loom_test {
use super::*;
use crate::testing::TestRegion;
use core::mem;
use loom::thread;
struct SendPtr(NonNull<u8>);
unsafe impl Send for SendPtr {}
unsafe fn forever<'a>(region: &'a Region<'a>) -> &'static Region<'static> {
unsafe { mem::transmute(region) }
}
fn layout() -> Layout {
Layout::from_size_align(8192, 8).unwrap()
}
#[test]
fn two_threads_never_claim_the_same_heap() {
loom::model(|| {
let test = TestRegion::new(1, 1);
let region = test.region();
let shared = unsafe { forever(®ion) };
let other = thread::spawn(move || shared.heap());
let mine = region.heap();
let theirs = other.join().unwrap();
assert!(mine.is_some() ^ theirs.is_some());
});
}
#[test]
fn concurrent_claims_each_find_a_free_slot() {
loom::model(|| {
let test = TestRegion::new(1, 2);
let region = test.region();
let shared = unsafe { forever(®ion) };
let other = thread::spawn(move || shared.heap());
let mine = region.heap();
let theirs = other.join().unwrap();
assert!(mine.is_some() && theirs.is_some(), "a claim failed with a free slot");
});
}
#[test]
fn a_claim_racing_a_release_finds_the_slot_or_leaves_it_free() {
loom::model(|| {
let test = TestRegion::new(1, 1);
let region = test.region();
let held = region.heap().unwrap();
let shared = unsafe { forever(®ion) };
let other = thread::spawn(move || shared.heap());
drop(held);
let theirs = other.join().unwrap();
assert!(theirs.is_some() != region.heap().is_some());
});
}
#[test]
fn threads_without_a_heap_never_share_a_spare() {
fn borrow_alone(region: &Region<'_>, inside: &AtomicBool) {
let (_, data) = region.borrow_spare(0);
assert!(!inside.swap(true, Ordering::Relaxed), "two threads borrowed one spare");
inside.store(false, Ordering::Relaxed);
data.release_claim();
}
loom::model(|| {
let test = TestRegion::new(1, 1).with_spare_heaps(1);
let region = test.region();
let inside = loom::sync::Arc::new(AtomicBool::new(false));
let shared = unsafe { forever(®ion) };
let theirs = loom::sync::Arc::clone(&inside);
let other = thread::spawn(move || borrow_alone(shared, &theirs));
borrow_alone(®ion, &inside);
other.join().unwrap();
});
}
#[test]
fn blocks_sent_while_the_owner_allocates_are_never_lost() {
loom::model(|| {
let test = TestRegion::new(2, 1);
let region = test.region();
let owner = region.heap().unwrap();
let layout = layout();
let blocks: std::vec::Vec<_> =
(0..16).map(|_| owner.alloc(layout).expect("sixteen blocks fit")).collect();
let (x, y) = (blocks[2], blocks[5]);
let (x_send, y_send) = (SendPtr(x), SendPtr(y));
let shared = unsafe { forever(®ion) };
let freer = thread::spawn(move || {
unsafe {
shared.dealloc(x_send.0, layout);
shared.dealloc(y_send.0, layout);
}
});
let mut got = std::vec![owner.alloc(layout)];
freer.join().unwrap();
while let Some(block) = owner.alloc(layout) {
got.push(Some(block));
}
let mut found: std::vec::Vec<_> = got.into_iter().flatten().collect();
found.sort();
let mut expected = std::vec![x, y];
expected.sort();
assert_eq!(found, expected, "a freed block went missing or appeared twice");
});
}
#[test]
fn two_senders_and_the_owner_reading_its_inbox_lose_nothing() {
loom::model(|| {
let test = TestRegion::new(1, 1);
let region = test.region();
let owner = region.heap().unwrap();
let layout = layout();
let blocks: std::vec::Vec<_> =
(0..8).map(|_| owner.alloc(layout).expect("eight blocks fit")).collect();
let (x, y) = (SendPtr(blocks[0]), SendPtr(blocks[1]));
let (one, two) = unsafe { (forever(®ion), forever(®ion)) };
let first = thread::spawn(move || {
let x = x;
unsafe { one.dealloc(x.0, layout) };
});
let second = thread::spawn(move || {
let y = y;
unsafe { two.dealloc(y.0, layout) };
});
unsafe { owner.data.drain_inbox(®ion) };
first.join().unwrap();
second.join().unwrap();
unsafe { owner.data.drain_inbox(®ion) };
let mut seen = std::collections::BTreeSet::new();
owner.validate_into(&mut seen);
assert!(
seen.contains(&blocks[0].as_ptr().addr()) &&
seen.contains(&blocks[1].as_ptr().addr())
);
});
}
}