From d308e7eadbb15c40e8ecd356d8b7a14e3d5d756d Mon Sep 17 00:00:00 2001 From: clabby Date: Sat, 14 Nov 2026 12:07:50 -0500 Subject: [PATCH] Let threads past max_heaps borrow spare heaps instead of failing A thread that found all max_heaps heaps taken got null from every allocation, so the program aborted at thread max_heaps + 1, 4097 by default. The global allocator's region now has spare heaps past max_heaps that Region::heap never hands out, four per online CPU and between 8 and 1024. A thread without a heap of its own borrows one for each allocation or resize: a compare-and-swap on the slot's claim, the operation as on a bound heap, and a store to release it. A spare keeps its bins and slabs from one borrower to the next. A thread asks for the spare it had last, or for its first borrow one hashed from its thread-local address, so threads that share the spares spread over them. A borrower that finds every spare taken spins for a moment and then yields. Frees from such a thread already went home through Region::dealloc without a heap, and still do. With one spare per CPU, 64 threads past the cap on 32 CPUs often found every spare held and yielded, and ran six times slower than with four per CPU. With four, they run at about a quarter of the speed of threads with a heap of their own, from 1 to 256 threads at once. Destructors that run after a thread's heap went back at exit, and allocations made while a thread binds its heap, used to claim a whole heap for one call and empty it afterwards. They borrow a spare now too. Region::heap counts the free slots and takes one before it looks for a slot, so a thread past the cap learns in one load that none is free, instead of a pass over every slot on every call, and it binds a heap of its own on its first call after one is given back. Binding writes the directory only once it has a heap, so threads that retry on every call do not keep writing the line that every free reads. trim empties the spares, and metrics count them. The fast paths are unchanged: only the binding, unbound and thread exit paths compile differently. --- DESIGN.md | 8 +- README.md | 4 +- crates/bcmalloc/src/config.rs | 8 +- crates/bcmalloc/src/global.rs | 142 +++++++++++++++++++++++++++++---- crates/bcmalloc/src/heap.rs | 136 ++++++++++++++++++++++++++----- crates/bcmalloc/src/region.rs | 124 ++++++++++++++++++++++++---- crates/bcmalloc/src/sync.rs | 11 ++- crates/bcmalloc/src/sys.rs | 9 +++ crates/bcmalloc/src/testing.rs | 19 +++++ crates/bcmalloc/src/tls.rs | 24 +++++- 10 files changed, 425 insertions(+), 60 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 508e0dd..bf4405e 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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. @@ -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 | @@ -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`. @@ -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. diff --git a/README.md b/README.md index 719e370..4cd8cc7 100644 --- a/README.md +++ b/README.md @@ -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. | @@ -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. diff --git a/crates/bcmalloc/src/config.rs b/crates/bcmalloc/src/config.rs index 7a651f7..d8e865a 100644 --- a/crates/bcmalloc/src/config.rs +++ b/crates/bcmalloc/src/config.rs @@ -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; diff --git a/crates/bcmalloc/src/global.rs b/crates/bcmalloc/src/global.rs index 4351282..9a5d7cd 100644 --- a/crates/bcmalloc/src/global.rs +++ b/crates/bcmalloc/src/global.rs @@ -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) @@ -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}, @@ -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; @@ -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); @@ -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) { @@ -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. @@ -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(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 { @@ -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(); diff --git a/crates/bcmalloc/src/heap.rs b/crates/bcmalloc/src/heap.rs index 56a3f78..c51ec10 100644 --- a/crates/bcmalloc/src/heap.rs +++ b/crates/bcmalloc/src/heap.rs @@ -450,28 +450,49 @@ impl HeapData { &self.private.events } - /// Tries to claim this slot as heap number `id` of the region. + /// Tries to claim this slot as heap number `id` of the region, for a thread to keep. pub(crate) fn claim(&self, id: u32, region: &Region<'_>) -> bool { - let won = !self.shared.claimed.load(Ordering::Relaxed) && - self.shared - .claimed - .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) - .is_ok(); + let won = self.try_take(); if won { - 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(); + self.adopt(id, region); + } + won + } + + /// Tries to take this slot, as heap number `id` of the region, for as long as one operation + /// takes. Unlike [`claim`](Self::claim), it keeps whatever the heap held when it was last + /// released, which is what spare heaps and `trim` want. Only the first taker sets it up. + 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 } + /// Takes the slot if no one holds it. + fn try_take(&self) -> bool { + !self.shared.claimed.load(Ordering::Relaxed) && + self.shared + .claimed + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + } + + /// Sets up a slot that was just taken as heap number `id` of the region. + 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(); + } + /// Makes the heap take its chunks from the part of the region of NUMA node `node`. fn settle_on(&self, region: &Region<'_>, node: usize) { self.private.node.set(node); @@ -576,11 +597,14 @@ impl HeapData { /// /// # Safety /// - /// The caller must hold the claim. + /// The caller must hold the claim, which [`Region::heap`] handed out. pub(crate) unsafe fn give_up(&self) { + // SAFETY: the claim was made on this region. + let region = unsafe { self.region() }; // SAFETY: forwarded. - unsafe { self.empty_caches(self.region()) }; + unsafe { self.empty_caches(region) }; self.release_claim(); + region.vacate(); } /// Gives the slot up for another thread to claim. @@ -2466,7 +2490,7 @@ impl<'r> Heap<'r> { } /// Gives up this handle without releasing the claim, which the caller takes over. The slot - /// stays claimed until [`release_claim`](HeapData::release_claim) is called on it. + /// stays claimed until [`give_up`](HeapData::give_up) is called on it. #[cfg(all(feature = "std", not(loom)))] pub(crate) const fn leak(self) -> &'r HeapData { let data = self.data; @@ -3234,6 +3258,42 @@ mod test { 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); + // SAFETY: the spare is borrowed until its claim is released. + 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"); + // SAFETY: as above. + let next = NonNull::new(unsafe { data.alloc(layout) }).unwrap(); + data.release_claim(); + let chunk = |block: NonNull| 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"); + + // Blocks of a spare go home to it like any other heap's, and trimming empties it. + // SAFETY: both blocks are live with this layout and freed once. + 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); @@ -3429,6 +3489,44 @@ mod loom_test { }); } + #[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(); + // SAFETY: the thread is joined below, before the region goes away. + let shared = unsafe { forever(®ion) }; + let other = thread::spawn(move || shared.heap()); + drop(held); + let theirs = other.join().unwrap(); + // The release was counted exactly once, so the slot is either theirs or free. + assert!(theirs.is_some() != region.heap().is_some()); + }); + } + + #[test] + fn threads_without_a_heap_never_share_a_spare() { + /// Borrows the spare and checks that no other thread is inside it. + 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)); + // SAFETY: the thread is joined below, before the region goes away. + 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(|| { diff --git a/crates/bcmalloc/src/region.rs b/crates/bcmalloc/src/region.rs index 7c0d308..5046191 100644 --- a/crates/bcmalloc/src/region.rs +++ b/crates/bcmalloc/src/region.rs @@ -24,6 +24,8 @@ //! A [`Region`] is the shared, thread-safe half of the allocator. Threads take a [`Heap`] from it //! to allocate. A [`Mapping`] owns the memory behind a region and unmaps it on drop. +#[cfg(any(test, feature = "std"))] +use crate::sync::yield_now; use crate::{ cache::CacheLine, chunks::{CHUNK_SHIFT, CHUNK_SIZE, Chunks}, @@ -60,6 +62,11 @@ const HUGE_PURGE_WAIT: u64 = 10; /// The chunks in one transparent huge page of 2 MiB. pub(crate) const HUGE_PAGE_CHUNKS: usize = (2 << 20) / CHUNK_SIZE; +/// How many passes over the spare heaps a borrower makes, pausing between them, before it yields +/// to other threads. +#[cfg(any(test, feature = "std"))] +const SPARE_SPINS: u32 = 16; + /// Why a region could not be created. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { @@ -107,6 +114,9 @@ pub struct Region<'a> { /// For every chunk of a slab, the owning heap and the class. See [`Entry`]. map: &'a [AtomicU64], heaps: &'a [HeapData], + /// How many slots at the end of `heaps` are spare heaps, which [`Region::heap`] never hands + /// out and threads without a heap of their own borrow one operation at a time. + spares: usize, /// The bin slots of every heap, [`BIN_SLOTS`] for each, owned by whoever claims the heap. bin_slots: *mut *mut Block, /// How many NUMA nodes the region is split between, into how many zones the part of each node @@ -117,6 +127,9 @@ pub struct Region<'a> { /// How many heap slots may have been claimed. Slots at or beyond it are untouched, so the /// operations that visit every slot stop here. claimed_mark: AtomicUsize, + /// How many of the slots that [`Region::heap`] hands out are not held. A claim takes one + /// before it looks for the slot, and giving a heap up returns it. + vacant: AtomicUsize, clock: Clock, occupancy: Occupancy, #[cfg(feature = "metrics")] @@ -170,7 +183,7 @@ unsafe impl Sync for Region<'_> {} /// long as `'a`, and used by nothing else. /// * `words` must be zeroed bitmap storage for `chunk_count` chunks, `slabs` must hold /// `chunk_count` unused descriptors, `map` `chunk_count` entries, and `heaps` unclaimed heap -/// slots. +/// slots, the last `spare_heaps` of which are spare heaps. /// * `bin_slots` must point to [`BIN_SLOTS`] writable pointers for each heap slot, valid for as /// long as `'a` and used by nothing else. pub(crate) struct Parts<'a> { @@ -180,6 +193,7 @@ pub(crate) struct Parts<'a> { pub(crate) slabs: &'a [Slab], pub(crate) map: &'a [AtomicU64], pub(crate) heaps: &'a [HeapData], + pub(crate) spare_heaps: usize, pub(crate) bin_slots: *mut *mut Block, /// How many NUMA nodes to split the chunks between, at least 1. pub(crate) nodes: usize, @@ -200,6 +214,7 @@ impl<'a> Region<'a> { // chunks must fit in the bits below it. See `Entry::huge`. debug_assert!(parts.heaps.len() <= Entry::HUGE_OWNER as usize); debug_assert!(parts.chunk_count < Entry::HUGE_OWNER as usize); + debug_assert!(parts.spare_heaps <= parts.heaps.len()); let words = Chunks::words_for(parts.chunk_count); // A region too small to give every node a word of its own is not split at all, because // the parts are numbered by physical node. Zones are given up first, since they only @@ -219,11 +234,13 @@ impl<'a> Region<'a> { slabs: parts.slabs, map: parts.map, heaps: parts.heaps, + spares: parts.spare_heaps, bin_slots: parts.bin_slots, nodes, zones, words, claimed_mark: AtomicUsize::new(0), + vacant: AtomicUsize::new(parts.heaps.len() - parts.spare_heaps), clock: Clock { _line: [], next_purge: AtomicU64::new(0), @@ -240,18 +257,88 @@ impl<'a> Region<'a> { /// Claims a free heap, or returns `None` if every one is in use. pub fn heap(&self) -> Option> { + if !self.take_vacancy() { + return None; + } // The search stops at the first free slot, so it only ever touches one slot that has never // been used. Bounding it by `claimed_mark` instead would make concurrent claims race for // that one slot and fail although others are free. - for (id, data) in self.heaps.iter().enumerate() { + for (id, data) in self.heaps[..self.heaps.len() - self.spares].iter().enumerate() { if data.claim(id as u32, self) { self.claimed_mark.fetch_max(id + 1, Ordering::Release); return Some(Heap::new(self, data)); } } + // A trim was holding the free slot for a moment. + self.vacate(); None } + /// Counts one free slot as taken, or returns false if none is free. When every slot is held + /// this costs one load, where a pass over all of them would cost one cache miss per slot, on + /// every call of a program with more threads than heaps. + fn take_vacancy(&self) -> bool { + let mut vacant = self.vacant.load(Ordering::Relaxed); + while vacant > 0 { + match self.vacant.compare_exchange_weak( + vacant, + vacant - 1, + Ordering::Acquire, + Ordering::Relaxed, + ) { + Ok(_) => return true, + Err(now) => vacant = now, + } + } + false + } + + /// Counts a slot that [`heap`](Self::heap) handed out as free again. Its claim must already be + /// released, so that a claim that takes the count finds the slot free. + pub(crate) fn vacate(&self) { + self.vacant.fetch_add(1, Ordering::Release); + } + + /// Borrows a spare heap for one operation, which the caller ends with + /// [`HeapData::release_claim`]. It tries spare number `hint`, reduced to the number of spares, + /// first and waits while every spare is held. Returns the number of the spare it took, the hint + /// for next time, and the heap. + /// + /// Spare heaps serve threads without a heap of their own: threads past the configured number of + /// heaps, and threads that gave theirs back at exit. A spare keeps its bins and slabs from one + /// borrower to the next, so a borrow costs one compare-and-swap. + #[cfg(any(test, feature = "std"))] + pub(crate) fn borrow_spare(&self, hint: usize) -> (usize, &HeapData) { + assert!(self.spares > 0, "the region has no spare heaps"); + let first = self.heaps.len() - self.spares; + let hint = if hint < self.spares { hint } else { hint % self.spares }; + let mut spins = 0; + loop { + for index in (hint..self.spares).chain(0..hint) { + let id = first + index; + if self.heaps[id].borrow(id as u32, self) { + return (index, &self.heaps[id]); + } + } + // A borrower holds a spare for one operation, but threads past the cap often outnumber + // the cores, so a waiter soon lets the holder run. Loom has to see a yield on every + // pass to explore the thread it waits for. + if cfg!(loom) || spins == SPARE_SPINS { + yield_now(); + } else { + spins += 1; + core::hint::spin_loop(); + } + } + } + + /// The slots that may hold memory, with their ids: those claimed so far and the spare heaps. + fn used_heaps(&self) -> impl Iterator + Clone { + let claimed = self.claimed_mark.load(Ordering::Acquire); + let spare = self.heaps.len() - self.spares; + (0..claimed).chain(spare..self.heaps.len()).map(|id| (id, &self.heaps[id])) + } + /// Frees a block without a heap, from any thread. /// /// This is what a thread uses when it has no heap of its own, for instance because it is being @@ -294,19 +381,19 @@ impl<'a> Region<'a> { /// While this drains a bitmap word the 64 chunks in it look allocated to everyone else, so run /// it when the program is not close to full. pub fn trim(&self) { - let claimed = self.claimed_mark.load(Ordering::Acquire); + let heaps = self.used_heaps(); // Flushing one heap can send blocks to another that was flushed before it, so a few more // passes take in what arrived. Each pass sends less, because a heap only sends blocks of // other heaps and those come to rest in their own slabs. for _ in 0..4 { - for (id, data) in self.heaps[..claimed].iter().enumerate() { - if data.claim(id as u32, self) { - // SAFETY: we just claimed the slot. + for (id, data) in heaps.clone() { + if data.borrow(id as u32, self) { + // SAFETY: we just took the slot. unsafe { data.flush(self) }; data.release_claim(); } } - if self.heaps[..claimed].iter().all(|data| data.is_claimed() || !data.has_mail()) { + if heaps.clone().all(|(_, data)| data.is_claimed() || !data.has_mail()) { break; } } @@ -330,25 +417,25 @@ impl<'a> Region<'a> { } } - /// A snapshot of the allocator's metrics, summed over every heap slot that has been claimed. - /// It costs a pass over those slots and the chunk bitmap, so call it now and then, not on a - /// hot path. See [`Metrics`](crate::Metrics). + /// A snapshot of the allocator's metrics, summed over every heap slot that has been claimed and + /// the spare heaps. It costs a pass over those slots and the chunk bitmap, so call it now and + /// then, not on a hot path. See [`Metrics`](crate::Metrics). #[cfg(feature = "metrics")] pub fn metrics(&self) -> crate::Metrics { use crate::metrics::Event; let claimed = self.claimed_mark.load(Ordering::Acquire); - let heaps = &self.heaps[..claimed]; + let heaps = self.used_heaps().map(|(_, heap)| heap); let counters = &self.counters; let classes = crate::metrics::class_metrics(|class| { let unbound = counters.frees[class.index()].get(); heaps - .iter() + .clone() .map(|heap| heap.class_counts(class)) .fold((0, unbound, 0), |(allocs, frees, slabs), (a, f, s)| { (allocs + a, frees + f, slabs.wrapping_add(s)) }) }); - let sum = |event| heaps.iter().map(|heap| heap.events().get(event)).sum::(); + let sum = |event| heaps.clone().map(|heap| heap.events().get(event)).sum::(); let huge_allocated = sum(Event::HugeBytesAllocated); let huge_freed = sum(Event::HugeBytesFreed) + counters.huge_bytes_freed.get(); let stats = self.stats(); @@ -864,11 +951,17 @@ impl Mapping { /// Fails if the configuration is unusable, the operating system refuses the reservation, or /// [`Commit::Lock`] cannot be honoured. pub fn new(config: &Config) -> Result { + Self::with_spare_heaps(config, 0) + } + + /// As [`new`](Self::new), with `spares` more heap slots that [`Region::heap`] never hands + /// out, for threads without a heap of their own to borrow. + pub(crate) fn with_spare_heaps(config: &Config, spares: usize) -> Result { let chunks = config.capacity_bytes() / CHUNK_SIZE; - let heaps = config.heap_count(); - if chunks == 0 || heaps == 0 { + if chunks == 0 || config.heap_count() == 0 { return Err(Error::InvalidConfig); } + let heaps = config.heap_count().checked_add(spares).ok_or(Error::InvalidConfig)?; let geometry = Geometry::new(chunks, heaps).ok_or(Error::InvalidConfig)?; let raw_len = geometry.total.checked_add(SLAB_ALIGN).ok_or(Error::InvalidConfig)?; let raw = sys::reserve(raw_len).ok_or(Error::OutOfAddressSpace)?; @@ -898,6 +991,7 @@ impl Mapping { slabs, map, heaps: heap_slots, + spare_heaps: spares, bin_slots: at(geometry.bins).cast::<*mut Block>(), nodes, huge_zone: config.wants_huge_pages() && cfg!(target_os = "linux"), diff --git a/crates/bcmalloc/src/sync.rs b/crates/bcmalloc/src/sync.rs index c467cc6..2c1e8d7 100644 --- a/crates/bcmalloc/src/sync.rs +++ b/crates/bcmalloc/src/sync.rs @@ -1,4 +1,4 @@ -//! The atomics the allocator is written against. +//! The atomics the allocator is written against, and the one way it waits for another thread. //! //! Normal builds use `core`'s atomics. Under `--cfg loom` the same names resolve to loom's //! instrumented versions, so the model checker can explore every interleaving of the lock-free @@ -12,3 +12,12 @@ pub(crate) use core::sync::atomic::{ pub(crate) use loom::sync::atomic::{ AtomicBool, AtomicPtr, AtomicU64, AtomicUsize, Ordering, fence, }; +#[cfg(loom)] +pub(crate) use loom::thread::yield_now; + +/// Lets other threads run, for a thread that waits on one of them. +#[cfg(all(not(loom), any(test, feature = "std")))] +pub(crate) fn yield_now() { + // SAFETY: sched_yield has no preconditions, and its only failure is not yielding. + unsafe { libc::sched_yield() }; +} diff --git a/crates/bcmalloc/src/sys.rs b/crates/bcmalloc/src/sys.rs index dd2ea59..94adfa4 100644 --- a/crates/bcmalloc/src/sys.rs +++ b/crates/bcmalloc/src/sys.rs @@ -208,6 +208,15 @@ pub(crate) fn monotonic_ms() -> u64 { } } +/// How many CPUs are online, or 1 if the system does not say. It reads no files and allocates +/// nothing, so the allocator can ask while it sets itself up. +#[cfg(all(feature = "std", not(loom)))] +pub(crate) fn online_cpus() -> usize { + // SAFETY: sysconf has no preconditions. + let cpus = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }; + usize::try_from(cpus).unwrap_or(1).max(1) +} + /// How many NUMA nodes the machine has, counting from node 0. It is 1 where the system does not /// say, the list of nodes has gaps, or the platform has no NUMA support to speak of. #[cfg_attr( diff --git a/crates/bcmalloc/src/testing.rs b/crates/bcmalloc/src/testing.rs index 5b421ed..d46430b 100644 --- a/crates/bcmalloc/src/testing.rs +++ b/crates/bcmalloc/src/testing.rs @@ -130,6 +130,7 @@ pub struct TestRegion { slabs: Box<[Slab]>, map: Box<[AtomicU64]>, heaps: Box<[HeapData]>, + spare_heaps: usize, bins: Box<[Cell<*mut Block>]>, memory: Buffer, chunks: usize, @@ -153,6 +154,7 @@ impl TestRegion { slabs: zeroed(chunks, Slab::new), map: zeroed(chunks, || AtomicU64::new(0)), heaps: zeroed(heaps, HeapData::new), + spare_heaps: 0, bins: zeroed(heaps * BIN_SLOTS, || Cell::new(ptr::null_mut())), memory: Buffer::new(chunks << CHUNK_SHIFT), chunks, @@ -175,6 +177,22 @@ impl TestRegion { Self { huge_zone: true, ..self } } + /// This region with `spares` spare heaps after its heap slots, which threads without a heap + /// of their own borrow, as the global allocator's region has. + #[must_use] + pub fn with_spare_heaps(self, spares: usize) -> Self { + let slots = self.heaps.len() + spares; + // SAFETY: as in `new`. + unsafe { + Self { + heaps: zeroed(slots, HeapData::new), + spare_heaps: spares, + bins: zeroed(slots * BIN_SLOTS, || Cell::new(ptr::null_mut())), + ..self + } + } + } + /// The region over this storage. pub fn region(&self) -> Region<'_> { // SAFETY: the buffer is 4 MiB aligned and `chunks` chunks long, and everything else was @@ -187,6 +205,7 @@ impl TestRegion { slabs: &self.slabs, map: &self.map, heaps: &self.heaps, + spare_heaps: self.spare_heaps, bin_slots: self.bins.as_ptr().cast::<*mut Block>().cast_mut(), nodes: self.nodes, huge_zone: self.huge_zone, diff --git a/crates/bcmalloc/src/tls.rs b/crates/bcmalloc/src/tls.rs index 0a3cbbb..7a7ab48 100644 --- a/crates/bcmalloc/src/tls.rs +++ b/crates/bcmalloc/src/tls.rs @@ -28,7 +28,7 @@ //! //! Once a thread's destructor has run, other destructors on that thread may still allocate or //! free. The slot is empty by then, and binding a new heap would hand a claim to a thread that will -//! never release it. [`exiting`] tells the slow path to use a temporary heap instead. +//! never release it. [`exiting`] tells the slow path to borrow a spare heap instead. use crate::heap::HeapData; use core::{cell::Cell, ffi::c_void, ptr}; @@ -45,6 +45,8 @@ thread_local! { /// Set while this thread is binding a heap. When the allocator replaces malloc, creating a key /// or storing a value may itself allocate, and that allocation must not try to bind again. static BINDING: Cell = const { Cell::new(false) }; + /// The spare heap this thread borrowed last, if it has no heap of its own, or `NO_SPARE`. + static SPARE: Cell = const { Cell::new(NO_SPARE) }; } /// Whether this thread is in the middle of binding a heap. @@ -57,6 +59,26 @@ pub(crate) fn set_binding(on: bool) { BINDING.with(|binding| binding.set(on)); } +/// A spare heap number that stands for a thread that has borrowed none yet. +const NO_SPARE: usize = usize::MAX; + +/// The spare heap this thread borrowed last, which it asks for first next time. Before its first +/// borrow a thread asks for one picked from the address of its own thread-local storage, so that +/// threads spread over the spares from the start. The region reduces the number to its spares. +pub(crate) fn spare() -> usize { + SPARE.with(|last| match last.get() { + // Thread-local blocks lie a stack apart, so their low bits are alike. A multiplicative + // hash moves the bits that differ into the top ones. + NO_SPARE => ptr::from_ref(last).addr().wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 48, + spare => spare, + }) +} + +/// Remembers the spare heap this thread borrowed. +pub(crate) fn set_spare(spare: usize) { + SPARE.with(|last| last.set(spare)); +} + /// Whether this thread has already given its heap back, so that it must not bind a new one. pub(crate) fn exiting() -> bool { EXITED.with(Cell::get)