use crate::{
chunks::CHUNK_SHIFT,
config::Config,
heap::HeapData,
region::{Entry, Error, Mapping, Region, Stats},
size_class::{MAX_SMALL, MIN_ALIGN, TABLE_MAX},
sync::{AtomicPtr, AtomicU64, AtomicUsize, Ordering},
sys, tls,
};
use core::{
alloc::{GlobalAlloc, Layout},
ptr::{self, NonNull},
};
const MIN_CAPACITY: usize = 256 << 20;
const SPARE_HEAPS_PER_CPU: usize = 4;
const MIN_SPARE_HEAPS: usize = 8;
const MAX_SPARE_HEAPS: usize = 1024;
const SMALL_ZEROED: usize = 1024;
fn set_out_of_memory() {
#[cfg(target_os = "linux")]
unsafe {
*libc::__errno_location() = libc::ENOMEM;
}
#[cfg(target_vendor = "apple")]
unsafe {
*libc::__error() = libc::ENOMEM;
}
}
#[derive(Debug)]
pub struct Bcmalloc {
config: Config,
region: AtomicPtr<Region<'static>>,
key: AtomicUsize,
directory: Directory,
}
#[derive(Debug)]
struct Directory {
base: AtomicUsize,
span: AtomicUsize,
map: AtomicPtr<AtomicU64>,
}
impl Directory {
const fn new() -> Self {
Self {
base: AtomicUsize::new(0),
span: AtomicUsize::new(0),
map: AtomicPtr::new(ptr::null_mut()),
}
}
fn publish(&self, region: &Region<'_>) {
self.base.store(region.chunk_ptr(0).addr(), Ordering::Relaxed);
self.span.store(region.span(), Ordering::Relaxed);
self.map.store(region.map_ptr().cast_mut(), Ordering::Relaxed);
}
#[inline(always)]
unsafe fn entry(&self, ptr: *const u8) -> Entry {
unsafe { self.entry_at(ptr.addr() - self.base.load(Ordering::Relaxed)) }
}
#[inline(always)]
unsafe fn entry_in_region(&self, ptr: *const u8) -> Option<Entry> {
let offset = ptr.addr().wrapping_sub(self.base.load(Ordering::Relaxed));
(offset < self.span.load(Ordering::Relaxed)).then(|| unsafe { self.entry_at(offset) })
}
#[inline(always)]
unsafe fn entry_at(&self, offset: usize) -> Entry {
let slot = unsafe { &*self.map.load(Ordering::Relaxed).add(offset >> CHUNK_SHIFT) };
Entry(slot.load(Ordering::Relaxed))
}
}
impl Bcmalloc {
pub const fn new() -> Self {
Self::with_config(Config::new())
}
pub const fn with_config(config: Config) -> Self {
Self {
config,
region: AtomicPtr::new(ptr::null_mut()),
key: AtomicUsize::new(tls::NO_KEY),
directory: Directory::new(),
}
}
pub const fn config(&self) -> &Config {
&self.config
}
pub fn stats(&self) -> Option<Stats> {
self.existing().map(Region::stats)
}
#[cfg(feature = "metrics")]
pub fn metrics(&self) -> Option<crate::Metrics> {
self.existing().map(Region::metrics)
}
pub fn trim(&self) {
if let Some(region) = self.existing() {
region.trim();
}
}
pub fn block_layout(&self, ptr: NonNull<u8>) -> Option<Layout> {
self.existing()?.block_layout(ptr.as_ptr())
}
#[inline]
pub fn malloc(&self, size: usize) -> *mut u8 {
if size <= TABLE_MAX &&
let Some(data) = self.thread_heap() &&
let Some(block) = data.pop_table(size, true)
{
return block;
}
self.malloc_slow(size)
}
#[cold]
#[inline(never)]
fn malloc_slow(&self, size: usize) -> *mut u8 {
let block = match self.thread_heap() {
Some(data) if size <= TABLE_MAX => unsafe { data.alloc_table(size, true) },
_ => {
Layout::from_size_align(size.max(1), MIN_ALIGN).map_or(ptr::null_mut(), |layout| {
unsafe { GlobalAlloc::alloc(self, layout) }
})
}
};
if block.is_null() {
set_out_of_memory();
}
block
}
#[inline]
pub fn calloc(&self, count: usize, size: usize) -> *mut u8 {
if let Some(bytes) = count.checked_mul(size) &&
bytes < SMALL_ZEROED &&
let Some(data) = self.thread_heap() &&
let Some(block) = data.pop_table(bytes, true)
{
unsafe { block.write_bytes(0, bytes) };
return block;
}
self.calloc_slow(count, size)
}
#[cold]
#[inline(never)]
fn calloc_slow(&self, count: usize, size: usize) -> *mut u8 {
let layout = count
.checked_mul(size)
.and_then(|bytes| Layout::from_size_align(bytes.max(1), MIN_ALIGN).ok());
let block = layout
.map_or(ptr::null_mut(), |layout| unsafe { GlobalAlloc::alloc_zeroed(self, layout) });
if block.is_null() {
set_out_of_memory();
}
block
}
#[inline]
pub fn usable_size(&self, ptr: NonNull<u8>) -> Option<usize> {
self.thread_heap().map_or_else(
|| self.block_layout(ptr).map(|layout| layout.size()),
|data| data.usable_size(ptr),
)
}
pub unsafe fn realloc_unsized(&self, ptr: NonNull<u8>, new_size: usize) -> *mut u8 {
let Some(size) = self.usable_size(ptr) else { return ptr::null_mut() };
if Layout::from_size_align(new_size, MIN_ALIGN).is_err() {
return ptr::null_mut();
}
unsafe {
let old = Layout::from_size_align_unchecked(size, MIN_ALIGN);
GlobalAlloc::realloc(self, ptr.as_ptr(), old, new_size)
}
}
#[inline]
pub unsafe fn free_unsized(&self, ptr: NonNull<u8>) {
let Some(data) = self.thread_heap() else {
return unsafe { self.free_unsized_unbound(ptr) };
};
if let Some(entry) = unsafe { self.directory.entry_in_region(ptr.as_ptr()) } {
unsafe { data.free_with_entry(ptr, entry) };
}
}
#[cold]
#[inline(never)]
unsafe fn free_unsized_unbound(&self, ptr: NonNull<u8>) {
if let Some(layout) = self.block_layout(ptr) {
unsafe { self.dealloc_unbound(ptr, layout) };
}
}
pub fn flush_thread(&self) {
if let (Some(data), Some(region)) = (self.bound_heap(), self.existing()) {
unsafe { data.flush(region) };
}
}
fn existing(&self) -> Option<&'static Region<'static>> {
unsafe { self.region.load(Ordering::Acquire).as_ref() }
}
#[inline]
fn region(&self) -> Option<&'static Region<'static>> {
self.existing().or_else(|| self.create())
}
#[cold]
fn create(&self) -> Option<&'static Region<'static>> {
let mut config = self.config;
let spares =
(SPARE_HEAPS_PER_CPU * sys::online_cpus()).clamp(MIN_SPARE_HEAPS, MAX_SPARE_HEAPS);
let mapping = loop {
match Mapping::with_spare_heaps(&config, spares) {
Ok(mapping) => break mapping,
Err(Error::OutOfAddressSpace) if config.capacity_bytes() / 2 >= MIN_CAPACITY => {
config = config.capacity(config.capacity_bytes() / 2);
}
Err(_) => return None,
}
};
let candidate = ptr::from_ref(mapping.region()).cast::<Region<'static>>().cast_mut();
match self.region.compare_exchange(
ptr::null_mut(),
candidate,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => Some(mapping.leak()),
Err(existing) => {
drop(mapping);
unsafe { existing.as_ref() }
}
}
}
}
impl Default for Bcmalloc {
fn default() -> Self {
Self::new()
}
}
impl Bcmalloc {
#[inline(always)]
fn thread_heap(&self) -> Option<&'static HeapData> {
tls::get(self.key.load(Ordering::Relaxed))
}
fn bound_heap(&self) -> Option<&'static HeapData> {
tls::lookup(self.key.load(Ordering::Relaxed))
}
fn key(&self) -> Option<usize> {
let key = self.key.load(Ordering::Acquire);
if key != tls::NO_KEY {
return Some(key);
}
let created = tls::create_key()?;
match self.key.compare_exchange(tls::NO_KEY, created, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => Some(created),
Err(existing) => {
tls::delete_key(created);
Some(existing)
}
}
}
#[cold]
fn bind(&self, region: &'static Region<'static>) -> Option<&'static HeapData> {
if tls::exiting() || tls::binding() {
return None;
}
tls::set_binding(true);
let bound = self.bind_now(region);
tls::set_binding(false);
bound
}
fn bind_now(&self, region: &'static Region<'static>) -> Option<&'static HeapData> {
let key = self.key()?;
let heap = region.heap()?;
self.directory.publish(region);
let data = heap.leak();
if tls::bind(key, data) {
Some(data)
} else {
unsafe { data.give_up() };
None
}
}
#[cold]
#[inline(never)]
unsafe fn alloc_unbound(&self, layout: Layout) -> *mut u8 {
if let Some(data) = self.bound_heap() {
return unsafe { data.alloc(layout) };
}
let Some(region) = self.region() else { return ptr::null_mut() };
if let Some(data) = self.bind(region) {
return unsafe { data.alloc(layout) };
}
with_spare(region, |data| unsafe { data.alloc(layout) })
}
#[cold]
#[inline(never)]
unsafe fn dealloc_unbound(&self, ptr: NonNull<u8>, layout: Layout) {
if let Some(data) = self.bound_heap() {
return unsafe { data.dealloc(ptr, layout) };
}
let Some(region) = self.existing() else { return };
if let Some(data) = self.bind(region) {
unsafe { data.dealloc(ptr, layout) };
} else {
unsafe { region.dealloc(ptr, layout) };
}
}
#[cold]
#[inline(never)]
unsafe fn realloc_unbound(&self, ptr: NonNull<u8>, layout: Layout, new_size: usize) -> *mut u8 {
if let Some(data) = self.bound_heap() {
return unsafe { data.realloc(ptr, layout, new_size) };
}
let Some(region) = self.existing() else { return ptr::null_mut() };
if let Some(data) = self.bind(region) {
return unsafe { data.realloc(ptr, layout, new_size) };
}
with_spare(region, |data| unsafe { data.realloc(ptr, layout, new_size) })
}
}
fn with_spare<T>(region: &Region<'_>, op: impl FnOnce(&HeapData) -> T) -> T {
let (spare, data) = region.borrow_spare(tls::spare());
tls::set_spare(spare);
let result = op(data);
data.release_claim();
result
}
unsafe impl GlobalAlloc for Bcmalloc {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if let Some(data) = self.thread_heap() {
return unsafe { data.alloc(layout) };
}
unsafe { self.alloc_unbound(layout) }
}
#[inline]
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
if let Some(data) = self.thread_heap() {
return unsafe { data.alloc_zeroed(layout) };
}
let block = unsafe { self.alloc_unbound(layout) };
if !block.is_null() {
unsafe { block.write_bytes(0, layout.size()) };
}
block
}
#[inline]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
let ptr = unsafe { NonNull::new_unchecked(ptr) };
let Some(data) = self.thread_heap() else {
return unsafe { self.dealloc_unbound(ptr, layout) };
};
if layout.size() <= MAX_SMALL {
unsafe { data.free_entry(ptr.as_ptr().cast(), self.directory.entry(ptr.as_ptr())) };
} else {
unsafe { data.dealloc(ptr, layout) };
}
}
#[inline]
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let ptr = unsafe { NonNull::new_unchecked(ptr) };
if let Some(data) = self.thread_heap() {
return unsafe { data.realloc(ptr, layout, new_size) };
}
unsafe { self.realloc_unbound(ptr, layout, new_size) }
}
}
#[cfg(all(test, not(loom), not(miri)))]
mod test {
use super::*;
use crate::config::Commit;
use core::alloc::Layout;
use std::{boxed::Box, vec::Vec};
fn instance() -> &'static Bcmalloc {
let config = Config::new().capacity(1 << 28).max_heaps(4).commit(Commit::Lazy);
Box::leak(Box::new(Bcmalloc::with_config(config)))
}
#[cfg(feature = "allocator-api")]
#[test]
fn collections_can_take_the_allocator_as_a_parameter() {
let allocator = instance();
let threads: Vec<_> = (0..4_u64)
.map(|seed| {
std::thread::spawn(move || {
let mut numbers = Vec::new_in(allocator);
numbers.extend((0..100_000).map(|i| i * seed));
assert_eq!(numbers[99_999], 99_999 * seed);
let boxed = Box::new_in([seed as u8; 64], allocator);
assert_eq!(boxed[63], seed as u8);
})
})
.collect();
for thread in threads {
thread.join().unwrap();
}
assert_eq!(allocator.stats().unwrap().heaps_in_use, 0);
}
#[cfg(feature = "allocator-api")]
#[test]
fn a_zero_sized_request_does_not_create_the_region() {
use core::alloc::Allocator;
let allocator = instance();
let empty = allocator.allocate(Layout::from_size_align(0, 32).unwrap()).unwrap();
assert_eq!(empty.len(), 0);
unsafe { allocator.deallocate(empty.cast(), Layout::from_size_align(0, 32).unwrap()) };
assert!(allocator.stats().is_none());
}
#[test]
fn a_block_can_be_freed_and_resized_with_the_layout_the_allocator_reports() {
let allocator = instance();
for (size, align) in [(1, 1), (100, 8), (5000, 64), (300_000, 4096), (3 << 20, 16)] {
let layout = Layout::from_size_align(size, align).unwrap();
let block = NonNull::new(unsafe { allocator.alloc(layout) }).unwrap();
let held = allocator.block_layout(block).unwrap();
assert!(held.size() >= size, "{size} fits in what the allocator holds");
let grown = unsafe { allocator.realloc(block.as_ptr(), held, held.size() * 2) };
let grown = NonNull::new(grown).unwrap();
let held = allocator.block_layout(grown).unwrap();
assert!(held.size() >= size * 2);
unsafe { allocator.dealloc(grown.as_ptr(), held) };
}
let outside = NonNull::from(&0_u64).cast::<u8>();
assert_eq!(allocator.block_layout(outside), None, "a pointer outside the region");
}
#[test]
fn frees_without_a_layout_return_everything_from_any_thread() {
let allocator = instance();
let sizes = [1, 100, 5000, 300_000, 3 << 20];
let blocks: Vec<_> = sizes
.iter()
.map(|&size| {
let layout = Layout::from_size_align(size, 16).unwrap();
NonNull::new(unsafe { allocator.alloc(layout) }).unwrap().addr().get()
})
.collect();
let (mine, theirs) = blocks.split_at(2);
let theirs = theirs.to_vec();
std::thread::spawn(move || {
for &addr in &theirs {
unsafe { allocator.free_unsized(NonNull::new(addr as *mut u8).unwrap()) };
}
})
.join()
.unwrap();
let mut outside = 0_u8;
unsafe {
for &addr in mine {
allocator.free_unsized(NonNull::new(addr as *mut u8).unwrap());
}
allocator.free_unsized(NonNull::from(&mut outside));
}
allocator.flush_thread();
allocator.trim();
let stats = allocator.stats().unwrap();
assert_eq!(stats.free, stats.capacity, "every block went back");
}
#[test]
fn malloc_serves_every_size_aligned_and_refuses_impossible_ones() {
let allocator = instance();
let sizes = [0, 1, 15, 16, 17, 8191, 8192, 8193, 100_000, 600_000, 5 << 20];
let blocks: Vec<_> = sizes.iter().map(|&size| (allocator.malloc(size), size)).collect();
for &(block, size) in &blocks {
assert!(!block.is_null(), "{size} bytes");
assert!(block.addr().is_multiple_of(16), "{size} bytes are aligned to 16");
let held = allocator.block_layout(NonNull::new(block).unwrap()).unwrap();
assert!(held.size() >= size.max(1), "{size} bytes fit in the block");
unsafe { block.write_bytes(0xa5, size) };
}
let distinct: std::collections::BTreeSet<_> = blocks.iter().map(|&(b, _)| b).collect();
assert_eq!(distinct.len(), blocks.len(), "a zero-sized request gets a block of its own");
assert!(allocator.malloc(usize::MAX).is_null());
assert!(allocator.malloc(usize::MAX / 2).is_null());
for (block, _) in blocks {
unsafe { allocator.free_unsized(NonNull::new(block).unwrap()) };
}
}
#[test]
fn c_style_resizing_and_sizes_need_no_layout() {
let allocator = instance();
let block = NonNull::new(allocator.malloc(100)).unwrap();
assert_eq!(allocator.usable_size(block), Some(112));
unsafe { block.as_ptr().write_bytes(7, 100) };
let same = unsafe { allocator.realloc_unsized(block, 60) };
assert_eq!(same, block.as_ptr(), "a block that still fits stays");
let grown = NonNull::new(unsafe { allocator.realloc_unsized(block, 300_000) }).unwrap();
assert_ne!(grown, block);
assert!(unsafe { core::slice::from_raw_parts(grown.as_ptr(), 60) }.iter().all(|&b| b == 7));
assert_eq!(allocator.usable_size(grown), Some(5 * (64 << 10)));
assert!(unsafe { allocator.realloc_unsized(grown, usize::MAX) }.is_null());
let mut outside = 0_u8;
assert_eq!(allocator.usable_size(NonNull::from(&mut outside)), None);
unsafe { allocator.free_unsized(grown) };
}
#[test]
fn a_thread_whose_first_call_resizes_or_zeroes_binds_a_heap() {
let allocator = instance();
let layout = Layout::from_size_align(100, 8).unwrap();
let block = unsafe { allocator.alloc(layout) }.addr();
std::thread::spawn(move || {
let block = ptr::with_exposed_provenance_mut::<u8>(block);
let grown = unsafe { allocator.realloc(block, layout, 5000) };
assert!(!grown.is_null());
unsafe { allocator.dealloc(grown, Layout::from_size_align(5000, 8).unwrap()) };
})
.join()
.unwrap();
std::thread::spawn(move || {
let zeroed = Layout::from_size_align(3000, 16).unwrap();
let block = unsafe { allocator.alloc_zeroed(zeroed) };
assert!(unsafe { core::slice::from_raw_parts(block, 3000) }.iter().all(|&b| b == 0));
unsafe { allocator.dealloc(block, zeroed) };
})
.join()
.unwrap();
assert_eq!(allocator.config().heap_count(), 4);
}
#[test]
fn threads_past_max_heaps_borrow_spares_until_a_heap_is_free() {
use std::sync::mpsc;
let allocator = instance();
let layout = Layout::from_size_align(100, 8).unwrap();
let (bound, all_bound) = mpsc::channel();
let mut holders: Vec<_> = (0..4)
.map(|_| {
let bound = bound.clone();
let (exit, told_to_exit) = mpsc::channel::<()>();
let thread = std::thread::spawn(move || {
unsafe { allocator.dealloc(allocator.alloc(layout), layout) };
bound.send(()).unwrap();
told_to_exit.recv().unwrap();
});
(exit, thread)
})
.collect();
for _ in 0..4 {
all_bound.recv().unwrap();
}
assert_eq!(allocator.stats().unwrap().heaps_in_use, 4);
let (borrowed, all_borrowed) = mpsc::channel();
let (go, told_to_go) = mpsc::channel::<()>();
let latecomer = std::thread::spawn(move || {
let block = unsafe { allocator.alloc(layout) };
assert!(!block.is_null());
let grown = unsafe {
block.write_bytes(5, 100);
allocator.realloc(block, layout, 300_000)
};
assert!(unsafe { core::slice::from_raw_parts(grown, 100) }.iter().all(|&b| b == 5));
unsafe { allocator.dealloc(grown, Layout::from_size_align(300_000, 8).unwrap()) };
let zeroed = NonNull::new(allocator.calloc(10, 100)).unwrap();
let bytes = unsafe { core::slice::from_raw_parts(zeroed.as_ptr(), 1000) };
assert!(bytes.iter().all(|&b| b == 0));
unsafe {
let moved = NonNull::new(allocator.realloc_unsized(zeroed, 5000)).unwrap();
allocator.free_unsized(moved);
}
assert!(allocator.bound_heap().is_none(), "no heap was free to bind");
borrowed.send(()).unwrap();
told_to_go.recv().unwrap();
unsafe { allocator.dealloc(allocator.alloc(layout), layout) };
assert!(
allocator.bound_heap().is_some(),
"the next call after a heap is free binds it"
);
});
all_borrowed.recv().unwrap();
let (exit, thread) = holders.remove(0);
exit.send(()).unwrap();
thread.join().unwrap();
go.send(()).unwrap();
latecomer.join().unwrap();
for (exit, thread) in holders {
exit.send(()).unwrap();
thread.join().unwrap();
}
assert_eq!(allocator.stats().unwrap().heaps_in_use, 0);
allocator.trim();
let stats = allocator.stats().unwrap();
assert_eq!(stats.free, stats.capacity, "the heaps and the spares gave everything back");
}
#[test]
fn flushing_a_thread_returns_what_its_heap_kept() {
let allocator = instance();
std::thread::spawn(move || {
let layout = Layout::new::<[u8; 100]>();
let blocks: Vec<_> = (0..1000).map(|_| unsafe { allocator.alloc(layout) }).collect();
for block in blocks {
unsafe { allocator.dealloc(block, layout) };
}
let held = allocator.stats().unwrap();
assert!(held.free < held.capacity, "the heap keeps some blocks and a slab");
allocator.flush_thread();
let after = allocator.stats().unwrap();
assert_eq!(after.free, after.capacity, "everything went back to the region");
})
.join()
.unwrap();
}
#[test]
fn a_thread_that_alternates_between_allocators_keeps_one_heap_in_each() {
let (first, second) = (instance(), instance());
let layout = Layout::from_size_align(64, 8).unwrap();
for _ in 0..20 {
for allocator in [first, second] {
unsafe {
let block = allocator.alloc(layout);
assert!(!block.is_null());
allocator.dealloc(block, layout);
}
}
}
assert_eq!(first.stats().unwrap().heaps_in_use, 1);
assert_eq!(second.stats().unwrap().heaps_in_use, 1);
}
}