Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,23 @@ jobs:
- name: Check every feature combination
run: just hack --locked

msrv:
name: Minimum Rust version
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout sources
uses: actions/checkout@v7
- name: Install Rust stable toolchain
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
cache-on-failure: true
- uses: taiki-e/install-action@just
- uses: taiki-e/install-action@cargo-hack
- name: Check every feature combination but allocator-api on the minimum version
run: just msrv --locked

lint:
name: Clippy and rustfmt
runs-on: ubuntu-latest
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# bcmalloc

<img src="https://img.shields.io/badge/license-Apache--2.0-blue.svg" alt="License"> <img src="https://img.shields.io/badge/rust-1.100%2B-orange.svg" alt="Rust 1.100+"> <img src="https://img.shields.io/badge/platforms-linux%20%7C%20macOS-lightgrey.svg" alt="Platforms">
<img src="https://img.shields.io/badge/license-Apache--2.0-blue.svg" alt="License"> <img src="https://img.shields.io/badge/rust-1.88%2B-orange.svg" alt="Rust 1.88+"> <img src="https://img.shields.io/badge/platforms-linux%20%7C%20macOS-lightgrey.svg" alt="Platforms">

A global allocator for long-lived, highly concurrent Rust programs. It reserves one region of address space up front and serves small blocks from per-thread stacks of free pointers, without atomic operations and without touching the blocks. Blocks freed by another thread go home in batched messages, one compare-and-swap per batch. Memory freed by one size class is reused by every other, memory that stays idle goes back to the operating system, and the capacity you configure is a hard limit.

Expand Down Expand Up @@ -47,16 +47,18 @@ unsafe { heap.dealloc(block, layout) };
# Ok::<(), bcmalloc::Error>(())
```

The allocator also implements the standard library's `Allocator` trait, which has been stable since Rust 1.100. A collection can then take it as a parameter without it being the global allocator. A heap implements the trait too, for code that wants one thread's heap.
With the `allocator-api` feature, the allocator also implements the standard library's `Allocator` trait, which has been stable since Rust 1.100. A collection can then take it as a parameter without it being the global allocator. A heap implements the trait too, for code that wants one thread's heap.

```rust
# #[cfg(feature = "allocator-api")] {
use bcmalloc::Bcmalloc;

static ALLOCATOR: Bcmalloc = Bcmalloc::new();

let mut numbers = Vec::new_in(&ALLOCATOR);
numbers.extend(0..1000_u32);
assert_eq!(numbers.iter().sum::<u32>(), 499_500);
# }
```

## Metrics
Expand Down Expand Up @@ -111,7 +113,7 @@ The development suite has 51 synthetic workloads and is what the allocator is tu
- A thread that finds all `max_heaps` heaps taken fails its allocations, which aborts the program.
- The capacity is a hard limit. Nothing grows the region after start-up.
- Linux and macOS are supported. Windows is not.
- The standard library's `Allocator` trait needs Rust 1.100 or later, which is the minimum supported version.
- The minimum supported Rust version is 1.88. The `allocator-api` feature needs 1.100, where the standard library's `Allocator` trait became stable.

## Testing

Expand Down
7 changes: 6 additions & 1 deletion crates/bcmalloc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
name = "bcmalloc"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
# The library's minimum, below the workspace's. The `allocator-api` feature needs 1.100.
rust-version = "1.88"
license.workspace = true
repository.workspace = true
description = "A scalable global allocator that reserves its memory up front, for long-lived, highly concurrent programs."
Expand All @@ -19,6 +20,10 @@ testing = [ "std" ]
# Counts allocations, frees, slabs and slow-path events per heap, for `Region::metrics` and
# `Bcmalloc::metrics`. The fast paths pay one add each on a cache line they already touch.
metrics = []
# Implements the standard library's `Allocator` trait for `Bcmalloc` and `Heap`, so that a
# collection can allocate from one without it being the global allocator. The trait needs Rust
# 1.100, above the crate's minimum.
allocator-api = []

[dependencies]
libc.workspace = true
Expand Down
95 changes: 72 additions & 23 deletions crates/bcmalloc/src/allocator.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! The [`Allocator`](core::alloc::Allocator) trait, for collections that take an allocator as a
//! parameter.
//! The [`Allocator`] trait, for collections that take an allocator as a parameter. It is compiled
//! with the `allocator-api` feature, because the trait needs Rust 1.100, above the crate's minimum.
//!
//! [`Bcmalloc`](crate::Bcmalloc) and [`Heap`](crate::Heap) both implement it, so a `Vec` or a
//! `Box` can allocate from one of them without it being the program's global allocator. Their
//! documentation has examples.
//! [`Bcmalloc`] and [`Heap`] both implement it, so a `Vec` or a `Box` can allocate from one of
//! them without it being the program's global allocator. The documentation of `Bcmalloc` has an
//! example.
//!
//! # How the trait's rules are met
//!
Expand All @@ -19,14 +19,21 @@
//! chunks can shrink or grow where it is. They always move it when the alignment changes, which
//! that resize does not support.

#![allow(clippy::incompatible_msrv, reason = "the allocator-api feature needs Rust 1.100")]

#[cfg(all(feature = "std", not(loom)))]
use crate::Bcmalloc;
use crate::Heap;
#[cfg(all(feature = "std", not(loom)))]
use core::alloc::GlobalAlloc;
use core::{
alloc::{AllocError, Layout},
alloc::{AllocError, Allocator, Layout},
num::NonZero,
ptr::{self, NonNull},
};

/// The operations that the allocator trait is built from.
pub(crate) trait Backend {
trait Backend {
/// Allocates a block, or returns null.
///
/// # Safety
Expand Down Expand Up @@ -68,7 +75,7 @@ fn block(ptr: *mut u8, size: usize) -> Result<NonNull<[u8]>, AllocError> {
NonNull::new(ptr).map(|ptr| NonNull::slice_from_raw_parts(ptr, size)).ok_or(AllocError)
}

pub(crate) fn allocate<A: Backend + ?Sized>(
fn allocate<A: Backend + ?Sized>(
backend: &A,
layout: Layout,
zeroed: bool,
Expand All @@ -83,11 +90,7 @@ pub(crate) fn allocate<A: Backend + ?Sized>(
block(ptr, layout.size())
}

pub(crate) unsafe fn deallocate<A: Backend + ?Sized>(
backend: &A,
ptr: NonNull<u8>,
layout: Layout,
) {
unsafe fn deallocate<A: Backend + ?Sized>(backend: &A, ptr: NonNull<u8>, layout: Layout) {
if layout.size() != 0 {
// SAFETY: the caller vouches for the block.
unsafe { backend.deallocate_raw(ptr, layout) };
Expand All @@ -100,7 +103,7 @@ pub(crate) unsafe fn deallocate<A: Backend + ?Sized>(
///
/// The block must be live with the old layout. The new size must be at least the old size when
/// growing and at most the old size when shrinking.
pub(crate) unsafe fn resize<A: Backend + ?Sized>(
unsafe fn resize<A: Backend + ?Sized>(
backend: &A,
ptr: NonNull<u8>,
old: Layout,
Expand Down Expand Up @@ -137,24 +140,24 @@ pub(crate) unsafe fn resize<A: Backend + ?Sized>(
block(moved, new.size())
}

/// Implements [`Allocator`](core::alloc::Allocator) for a type that implements [`Backend`].
/// Implements [`Allocator`] for a type that implements [`Backend`].
macro_rules! allocator {
($($header:tt)*) => {
// SAFETY: the blocks come from the backend, which hands out valid, aligned, disjoint memory
// that stays valid until it is freed, however the handle is moved or copied. Zero-sized
// blocks are dangling and aligned, as the trait allows.
unsafe impl $($header)* {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
$crate::allocator::allocate(self, layout, false)
allocate(self, layout, false)
}

fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
$crate::allocator::allocate(self, layout, true)
allocate(self, layout, true)
}

unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
// SAFETY: forwarded.
unsafe { $crate::allocator::deallocate(self, ptr, layout) }
unsafe { deallocate(self, ptr, layout) }
}

unsafe fn grow(
Expand All @@ -164,7 +167,7 @@ macro_rules! allocator {
new: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// SAFETY: forwarded.
unsafe { $crate::allocator::resize(self, ptr, old, new, false) }
unsafe { resize(self, ptr, old, new, false) }
}

unsafe fn grow_zeroed(
Expand All @@ -174,7 +177,7 @@ macro_rules! allocator {
new: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// SAFETY: forwarded.
unsafe { $crate::allocator::resize(self, ptr, old, new, true) }
unsafe { resize(self, ptr, old, new, true) }
}

unsafe fn shrink(
Expand All @@ -184,18 +187,64 @@ macro_rules! allocator {
new: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// SAFETY: forwarded.
unsafe { $crate::allocator::resize(self, ptr, old, new, false) }
unsafe { resize(self, ptr, old, new, false) }
}
}
};
}
pub(crate) use allocator;

impl Backend for Heap<'_> {
unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 {
self.alloc(layout).map_or(ptr::null_mut(), NonNull::as_ptr)
}

unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 {
self.alloc_zeroed(layout).map_or(ptr::null_mut(), NonNull::as_ptr)
}

unsafe fn deallocate_raw(&self, ptr: NonNull<u8>, layout: Layout) {
// SAFETY: forwarded.
unsafe { self.dealloc(ptr, layout) };
}

unsafe fn resize_raw(&self, ptr: NonNull<u8>, old: Layout, new_size: usize) -> *mut u8 {
// SAFETY: forwarded.
unsafe { self.realloc(ptr, old, new_size) }.map_or(ptr::null_mut(), NonNull::as_ptr)
}
}

allocator!(Allocator for Heap<'_>);

#[cfg(all(feature = "std", not(loom)))]
impl Backend for Bcmalloc {
unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 {
// SAFETY: forwarded.
unsafe { GlobalAlloc::alloc(self, layout) }
}

unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 {
// SAFETY: forwarded.
unsafe { GlobalAlloc::alloc_zeroed(self, layout) }
}

unsafe fn deallocate_raw(&self, ptr: NonNull<u8>, layout: Layout) {
// SAFETY: forwarded.
unsafe { GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) };
}

unsafe fn resize_raw(&self, ptr: NonNull<u8>, old: Layout, new_size: usize) -> *mut u8 {
// SAFETY: forwarded.
unsafe { GlobalAlloc::realloc(self, ptr.as_ptr(), old, new_size) }
}
}

#[cfg(all(feature = "std", not(loom)))]
allocator!(Allocator for Bcmalloc);

#[cfg(all(test, not(loom)))]
mod test {
use super::*;
use crate::testing::{TestRegion, iterations};
use core::alloc::Allocator;
use std::{boxed::Box, vec::Vec};

fn layout(size: usize, align: usize) -> Layout {
Expand Down
47 changes: 16 additions & 31 deletions crates/bcmalloc/src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
//! or when more threads are running than the configuration has heaps for.

use crate::{
allocator::{Backend, allocator},
chunks::CHUNK_SHIFT,
config::Config,
heap::{Heap, HeapData},
Expand All @@ -39,7 +38,7 @@ use crate::{
tls,
};
use core::{
alloc::{AllocError, Allocator, GlobalAlloc, Layout},
alloc::{GlobalAlloc, Layout},
ptr::{self, NonNull},
};

Expand Down Expand Up @@ -96,10 +95,12 @@ fn set_out_of_memory() {
///
/// # As an `Allocator`
///
/// A `Bcmalloc` can also serve a single collection through the standard library's
/// [`Allocator`] trait, whether or not it is the global allocator.
/// With the `allocator-api` feature, a `Bcmalloc` can also serve a single collection through
/// the standard library's [`Allocator`](core::alloc::Allocator) trait, whether or not it is the
/// global allocator.
///
/// ```
/// # #[cfg(feature = "allocator-api")] {
/// use bcmalloc::Bcmalloc;
///
/// static ALLOCATOR: Bcmalloc = Bcmalloc::new();
Expand All @@ -110,6 +111,7 @@ fn set_out_of_memory() {
///
/// let boxed = Box::new_in([7_u8; 100], &ALLOCATOR);
/// assert_eq!(boxed[99], 7);
/// # }
/// ```
///
/// A zero-sized request never reaches the allocator. A block is exactly as long as it was asked to
Expand Down Expand Up @@ -436,30 +438,6 @@ impl Bcmalloc {
}
}

impl Backend for Bcmalloc {
unsafe fn allocate_raw(&self, layout: Layout) -> *mut u8 {
// SAFETY: forwarded.
unsafe { GlobalAlloc::alloc(self, layout) }
}

unsafe fn allocate_zeroed_raw(&self, layout: Layout) -> *mut u8 {
// SAFETY: forwarded.
unsafe { GlobalAlloc::alloc_zeroed(self, layout) }
}

unsafe fn deallocate_raw(&self, ptr: NonNull<u8>, layout: Layout) {
// SAFETY: forwarded.
unsafe { GlobalAlloc::dealloc(self, ptr.as_ptr(), layout) };
}

unsafe fn resize_raw(&self, ptr: NonNull<u8>, old: Layout, new_size: usize) -> *mut u8 {
// SAFETY: forwarded.
unsafe { GlobalAlloc::realloc(self, ptr.as_ptr(), old, new_size) }
}
}

allocator!(Allocator for Bcmalloc);

impl Default for Bcmalloc {
fn default() -> Self {
Self::new()
Expand Down Expand Up @@ -660,6 +638,7 @@ mod test {
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();
Expand All @@ -682,8 +661,10 @@ mod test {
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);
Expand Down Expand Up @@ -828,9 +809,13 @@ mod test {
fn flushing_a_thread_returns_what_its_heap_kept() {
let allocator = instance();
std::thread::spawn(move || {
let blocks: Vec<_> =
(0..1000).map(|i| Box::new_in([i as u8; 100], allocator)).collect();
drop(blocks);
let layout = Layout::new::<[u8; 100]>();
// SAFETY: the layout is not zero sized.
let blocks: Vec<_> = (0..1000).map(|_| unsafe { allocator.alloc(layout) }).collect();
for block in blocks {
// SAFETY: each block came from this allocator with this layout and is freed once.
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();
Expand Down
Loading
Loading