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
8 changes: 5 additions & 3 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ Each bin is a range of pointer slots in the region, with its top pointer kept ne

**Heap lifetime.** A heap is a slot in the region and not a property of a thread. When a thread exits, its heap empties its bins and outboxes and goes back to the pool with all its slabs, and the next thread to start takes it. A thread that is about to go quiet can call `Bcmalloc::flush_thread` to hand back what its heap keeps, as jemalloc's thread cache flush does.

**Threads without a heap.** The global allocator's region has spare heaps past `max_heaps` that no thread binds, four per online CPU and between 8 and 1024, so that the threads that run at once seldom find every spare held. A thread that finds every heap taken, or that runs destructors after its own heap went back at exit, borrows a spare for each allocation. The borrow is a compare-and-swap on the slot's claim, the allocation runs on the spare as it would on a bound heap, and a store releases the slot. A spare keeps its bins and slabs from one borrower to the next. A thread asks first for the spare it had last, and for its first borrow for one picked from the address of its thread-local storage, so that threads sharing the spares spread over them. A borrower that finds every spare taken spins for a moment and then yields. Its frees go home through the region without a heap, as a free from an exiting thread does. A count of the free heap slots tells such a thread in one load that none is free, where a pass over the slots would cost a cache miss for each of 4096, and the thread binds a heap of its own on its first call after one is given back. `trim` empties the spares along with the idle heaps.

## 7. Freeing from another thread

A free reads the chunk map entry of the block, which names the heap that owns its slab. If that is the calling thread's heap, the block goes into the bin. Otherwise there are two cases.
Expand Down Expand Up @@ -224,7 +226,7 @@ Concurrency bugs hide from tests that pass, so the allocator is checked in sever

| Tool | What it covers |
| -------------------- | ----------------------------------------------------------------------------------------------------- |
| loom | Every interleaving of the chunk bitmap, a purge pass and its flag, heap claims, and inbox pushes |
| loom | Every interleaving of the chunk bitmap, a purge pass and its flag, heap claims, borrows, inbox pushes |
| Miri | All unit tests under strict provenance, on the portable thread lookup |
| fuzzing | Random operation sequences against a model, with a validator that checks every structure after a step |
| unit tests | Every module, including a causal test for each bug found, with line coverage reported to Codecov |
Expand Down Expand Up @@ -252,7 +254,7 @@ The design spends a little memory and some bookkeeping to keep three things chea

These are the costs.

- **Metadata.** The free bitmaps make a slab descriptor 640 bytes, so metadata is about 1% of the managed memory instead of a fraction of that, and every heap slot reserves about 280 KiB of address space for bin slots. All of it is address space until it is used, but a small region with the default 4096 heaps reserves more for bins than for blocks, so small regions should set `max_heaps` to what they need.
- **Metadata.** The free bitmaps make a slab descriptor 640 bytes, so metadata is about 1% of the managed memory instead of a fraction of that, and every heap slot reserves about 280 KiB of address space for bin slots, spare heaps included. All of it is address space until it is used, unless `Commit::Lock` pins the region, but a small region with the default 4096 heaps still reserves more for bins than for blocks, so small regions should set `max_heaps` to what they need.
- **Bursts larger than a bin.** A block that overflows a bin goes back to its slab and comes out again on the next refill, one bitmap operation each way, where a list would move a whole chain at once. Bins that keep overflowing grow to make this rare, within a budget.
- **Most remote frees go home.** Except for small blocks that own their lines, the freeing thread cannot keep a block, so a producer and a consumer pay one message per batch, and blocks wait in an outbox until it fills, is needed for another destination, or is flushed.
- **Per-thread caches hold memory.** A heap's bins and outboxes keep blocks that other threads cannot use until the heap flushes them, and a thread that goes quiet keeps them until it exits or calls `flush_thread`.
Expand All @@ -261,7 +263,7 @@ These are the costs.
## 14. Limits

- Alignments above 4 MiB are refused. A request aligned to more than 64 KiB takes a run of whole chunks of its own, at least 128 KiB, whatever its size.
- A thread that finds every heap taken fails its allocations, which aborts the program. `max_heaps` is a design-time bound, like TigerBeetle's connection limit.
- Threads past `max_heaps` share the spare heaps, four per online CPU and at most 1024, one call at a time. They do not fail, but each call costs a few times what it costs a thread with a heap of its own, and more of them allocating at once than there are spares wait on each other, so `max_heaps` should still cover the threads a program runs at once.
- Allocations over 4 MiB claim several bitmap words and are obstruction-free, not lock-free.
- The capacity is a hard limit. A purge pass or a trim makes some chunks look allocated while it holds them, so a request that needs those chunks waits for the pass to finish. It does not fail.
- A heap holds blocks in its bins and outboxes until it needs them, fills a message, or is flushed. A thread that goes quiet keeps them until it exits or calls `flush_thread`. The bins of one heap hold at most their initial capacity plus 2 MiB.
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ The C library prints the same report at exit when it is built with the feature a
| Option | Default | What it does |
| ------------ | ------- | -------------------------------------------------------------------------------- |
| `capacity` | 64 GiB | Size of the region. It is address space until memory is touched. |
| `max_heaps` | 4096 | How many threads can allocate at once. |
| `max_heaps` | 4096 | How many threads get a heap of their own. |
| `commit` | `Lazy` | `Populate` backs every page now and `Lock` also pins them in RAM. |
| `huge_pages` | on | Huge pages on Linux for big heaps, big processes and big blocks. macOS has none. |
| `numa` | on | Splits the region between NUMA nodes on Linux machines with several. |
Expand All @@ -110,7 +110,7 @@ The development suite has 51 synthetic workloads and is what the allocator is tu
- The capacity is a hard limit. Nothing grows the region after start-up, and an allocation that does not fit fails. Through the global allocator, a failed allocation aborts the program.
- The default region is 64 GiB of address space. Under strict overcommit (`vm.overcommit_memory=2`), or with a limit on a process's data or address space, the kernel counts all of it. The global allocator then retries with half the capacity until the reservation fits, down to 256 MiB.
- Alignments above 4 MiB are refused, and the allocation fails. A request aligned to more than 64 KiB takes a run of whole chunks of its own, at least 128 KiB, whatever its size.
- A thread that finds all `max_heaps` heaps taken fails its allocations.
- Threads past `max_heaps` share a few spare heaps, one call at a time. They do not fail, but they allocate more slowly than threads with a heap of their own, so set `max_heaps` to the most threads the program runs at once.
- Idle memory goes back to the operating system from the allocator's slower operations, such as refilling a thread's cache, and not from a background thread. A program that goes quiet keeps what it freed until it allocates enough to reach one of them, or until it calls [`Bcmalloc::trim`](https://docs.rs/bcmalloc/latest/bcmalloc/struct.Bcmalloc.html#method.trim).
- A region backed up front with `Commit::Populate` or `Commit::Lock` keeps every page and gives nothing back. So does any region once the kernel refuses to take pages back, as it does for memory the program has locked, for example with `mlockall`.
- It builds for 64-bit Linux and macOS. Other Unix systems are untested, and other systems, Windows among them, are refused at compile time.
Expand Down
8 changes: 5 additions & 3 deletions crates/bcmalloc/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,12 @@ impl Config {
self
}

/// Sets how many threads can allocate at once.
/// Sets how many threads get a heap of their own.
///
/// Each running thread holds one heap, and a thread that finds none free fails its allocations,
/// so set it to the most threads the program runs at once, with some room to spare.
/// Each running thread holds one heap. Through [`Bcmalloc`](crate::Bcmalloc), threads past
/// this many share a few spare heaps, one call at a time, which is slower, and a
/// [`Region`](crate::Region) used directly hands out no more heaps than this. Set it to the
/// most threads the program runs at once, with some room to spare.
#[must_use]
pub const fn max_heaps(mut self, heaps: usize) -> Self {
self.max_heaps = heaps;
Expand Down
142 changes: 126 additions & 16 deletions crates/bcmalloc/src/global.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! The `#[global_allocator]` front end.
//!
//! [`Bcmalloc`] is a `static` that creates its [`Region`] the first time anything allocates, and
//! gives every thread a [`Heap`] of its own. After that a call looks like this.
//! gives every thread a [`Heap`](crate::Heap) of its own. After that a call looks like this.
//!
//! ```text
//! alloc(layout)
Expand All @@ -19,23 +19,32 @@
//!
//! A thread binds its heap on its first allocation or free, and a key destructor releases the
//! heap when the thread exits. Other destructors may still allocate or free after that one has
//! run. At that point the slot is empty and the thread is marked as gone, so frees fall back to
//! [`Region`::dealloc] and allocations borrow a heap for just that one call.
//! run. At that point the slot is empty and the thread is marked as gone, so it has no heap of its
//! own, as described next.
//!
//! # Threads without a heap
//!
//! The region has a few spare heaps past `max_heaps` that no thread binds. A thread that finds
//! every heap taken, or that gave its heap back at exit, borrows a spare for each allocation with
//! one compare-and-swap and gives it back when the call returns. Its frees go home through
//! [`Region::dealloc`], which needs no heap. Such a thread binds a heap of its own on its first
//! call after one is given back. The spares are shared, so these threads allocate more slowly than
//! threads with a heap, but they do not fail for want of one.
//!
//! # Failure
//!
//! A failed allocation returns null, and the standard library turns that into an abort. That
//! happens when the region is full, when the alignment is above [`MAX_ALIGN`](crate::MAX_ALIGN),
//! or when more threads are running than the configuration has heaps for.
//! happens when the region is full or when the alignment is above
//! [`MAX_ALIGN`](crate::MAX_ALIGN).

use crate::{
chunks::CHUNK_SHIFT,
config::Config,
heap::{Heap, HeapData},
heap::HeapData,
region::{Entry, Error, Mapping, Region, Stats},
size_class::{MAX_SMALL, MIN_ALIGN, TABLE_MAX},
sync::{AtomicPtr, AtomicU64, AtomicUsize, Ordering},
tls,
sys, tls,
};
use core::{
alloc::{GlobalAlloc, Layout},
Expand All @@ -45,6 +54,16 @@ use core::{
/// The smallest region the lazy start-up settles for when the OS refuses a bigger one.
const MIN_CAPACITY: usize = 256 << 20;

/// How many spare heaps the region has for threads without a heap of their own, per online CPU.
/// With one per CPU, the threads that run at once often found every spare held and had to yield,
/// and 64 threads on 32 CPUs allocated six times slower than with four.
const SPARE_HEAPS_PER_CPU: usize = 4;

/// The bounds on the number of spare heaps. Each costs as much address space as a heap slot, and
/// memory only once a thread uses it.
const MIN_SPARE_HEAPS: usize = 8;
const MAX_SPARE_HEAPS: usize = 1024;

/// Zeroed requests below this many bytes are cleared without asking whether the memory is fresh,
/// as [`HeapData::alloc_zeroed`] does.
const SMALL_ZEROED: usize = 1024;
Expand Down Expand Up @@ -411,8 +430,10 @@ impl Bcmalloc {
#[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::new(&config) {
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);
Expand Down Expand Up @@ -489,10 +510,11 @@ impl Bcmalloc {

/// The body of [`bind`](Self::bind), which runs with the binding flag set.
fn bind_now(&self, region: &'static Region<'static>) -> Option<&'static HeapData> {
// The fast frees read the directory once this thread has a heap.
self.directory.publish(region);
let key = self.key()?;
let heap = region.heap()?;
// The fast frees read the directory once this thread has a heap. A thread that finds no
// heap does not write it, because it tries again on every call and every free reads it.
self.directory.publish(region);
// The heap releases its claim if the system refuses to remember it.
let data = heap.leak();
if tls::bind(key, data) {
Expand All @@ -517,7 +539,8 @@ impl Bcmalloc {
// SAFETY: binding claimed the heap for this thread.
return unsafe { data.alloc(layout) };
}
region.heap().and_then(|heap| heap.alloc(layout)).map_or(ptr::null_mut(), NonNull::as_ptr)
// SAFETY: the spare is borrowed for the call.
with_spare(region, |data| unsafe { data.alloc(layout) })
}

/// Frees for a thread that has no heap yet.
Expand Down Expand Up @@ -555,14 +578,23 @@ impl Bcmalloc {
// block and the size.
return unsafe { data.realloc(ptr, layout, new_size) };
}
let resize = |heap: &Heap<'_>| {
// SAFETY: the caller vouches for the block and the size.
unsafe { heap.realloc(ptr, layout, new_size) }
};
region.heap().and_then(|heap| resize(&heap)).map_or(ptr::null_mut(), NonNull::as_ptr)
// SAFETY: the spare is borrowed for the call, and the caller vouches for the block and the
// size.
with_spare(region, |data| unsafe { data.realloc(ptr, layout, new_size) })
}
}

/// Runs `op` on a spare heap of `region`, for a thread that has no heap of its own. The thread
/// asks for the spare it had last time, so that threads sharing the spares settle on different
/// ones.
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
}

// SAFETY: every method forwards to a heap or region of the allocator, which return blocks that
// are valid, aligned, disjoint and live until freed, and never unwind.
unsafe impl GlobalAlloc for Bcmalloc {
Expand Down Expand Up @@ -806,6 +838,84 @@ mod test {
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();
// Four threads take every heap and keep them until they are told to exit.
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 || {
// SAFETY: the layout is not zero sized, and the block is freed once.
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 || {
// Every heap is taken, so each call borrows a spare.
// SAFETY: the layout is not zero sized.
let block = unsafe { allocator.alloc(layout) };
assert!(!block.is_null());
// SAFETY: the block holds 100 bytes, is live with its layout, and the new size is
// valid.
let grown = unsafe {
block.write_bytes(5, 100);
allocator.realloc(block, layout, 300_000)
};
// SAFETY: the grown block holds at least 100 bytes.
assert!(unsafe { core::slice::from_raw_parts(grown, 100) }.iter().all(|&b| b == 5));
// SAFETY: the grown block is live with the new size, and is freed once.
unsafe { allocator.dealloc(grown, Layout::from_size_align(300_000, 8).unwrap()) };
let zeroed = NonNull::new(allocator.calloc(10, 100)).unwrap();
// SAFETY: the block holds 1000 bytes.
let bytes = unsafe { core::slice::from_raw_parts(zeroed.as_ptr(), 1000) };
assert!(bytes.iter().all(|&b| b == 0));
// SAFETY: the block is live, the size is not zero, and the result is freed once.
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();
// SAFETY: as for the first block.
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();
// Joining a thread waits for its key destructor, which gives its heap back.
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();
Expand Down
Loading
Loading