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
4 changes: 3 additions & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Section 10 explains how huge pages are kept whole once they are in use.

**NUMA.** On a machine with more than one NUMA node, the chunks are split into one contiguous part per node, and each part asks the kernel to prefer its node's memory. A heap takes its slabs from the part of the node its thread was running on when it claimed the heap, and borrows from the other parts only when its own is full. A thread's memory therefore sits on its own node without the allocator ever asking where it runs on the fast path.

The configuration decides how eager to be. `Commit::Lazy` touches nothing. `Commit::Populate` backs every page before the first allocation, and `Commit::Lock` also pins them. With those, a program gets TigerBeetle's posture directly. The memory is resident from the start, there are no page faults on the allocation path, and the capacity is a hard limit.
The configuration decides how eager to be. `Commit::Lazy` touches nothing. `Commit::Populate` backs every page before the first allocation, and `Commit::Lock` also pins them. With those, a program gets TigerBeetle's posture directly. The memory is resident from the start and stays resident, because such a region never gives pages back, there are no page faults on the allocation path, and the capacity is a hard limit.

## 4. Chunks

Expand Down Expand Up @@ -210,6 +210,8 @@ A pass makes free chunks look allocated while it holds them. If a pass holds eve

`trim` is the explicit version. It empties every heap that no thread holds, then gives back every free chunk, whole huge page or not, because the caller asked for it.

Some regions keep their pages. One backed up front with `Commit::Populate` or `Commit::Lock` asked to stay resident, so its clock never runs and `trim` only empties heaps. The kernel also refuses to discard pages that are locked in memory, which happens when a program pins its memory with `mlockall`, and those pages keep their contents. A chunk is recorded as given back only when the kernel took its pages, so a zeroed request never trusts a refused run to read as zeros, and the first refusal makes the region keep its pages from then on, since asking again would only be refused again.

## 11. Metrics

With the `metrics` feature, every heap counts what it does, and `Bcmalloc::metrics` or `Region::metrics` sums the counts into a snapshot. For each size class it has the blocks allocated and freed and the slabs held, from which the live bytes and the share of the class's slabs in use follow. It also counts refills, slabs taken and given back, blocks sent home and the messages that carried them, reads of the inbox, huge blocks and the requests the heap's cache of them served, bins that grew and shrank, zeroed requests served from fresh memory, and the work of the purge clock. The snapshot prints as a report, and the C library prints it at exit when `BCMALLOC_SHOW_METRICS` is set, as mimalloc does with `MIMALLOC_SHOW_STATS`.
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<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 href="https://codecov.io/gh/clabby/bcmalloc"><img src="https://codecov.io/gh/clabby/bcmalloc/graph/badge.svg" alt="Coverage"></a>

bcmalloc is a global allocator for Rust programs that run for a long time on many threads. It reserves its address space once, at a size you choose, and never grows past it, so the program's memory has a hard ceiling, while the pages inside are only backed as they are used and go back to the operating system when they fall idle. Each thread allocates and frees through its own heap without atomic instructions, and blocks freed on another thread go home in batches, one compare-and-swap per batch. It is faster than mimalloc, jemalloc and snmalloc on [mimalloc-bench](https://github.com/daanx/mimalloc-bench) and on the held-out Rust programs on Linux, and on mimalloc-bench it holds about two thirds of mimalloc's peak memory. A program that wants its memory resident from the start can back or pin the whole region before its first allocation with [`Commit::Populate`](https://docs.rs/bcmalloc/latest/bcmalloc/enum.Commit.html#variant.Populate) or [`Commit::Lock`](https://docs.rs/bcmalloc/latest/bcmalloc/enum.Commit.html#variant.Lock). [DESIGN.md](https://github.com/clabby/bcmalloc/blob/main/DESIGN.md) explains how it works, and [BENCHMARKS.md](https://github.com/clabby/bcmalloc/blob/main/BENCHMARKS.md) has every measurement.
bcmalloc is a global allocator for Rust programs that run for a long time on many threads. It reserves its address space once, at a size you choose, and never grows past it, so the program's memory has a hard ceiling, while the pages inside are only backed as they are used and go back to the operating system when they fall idle. Each thread allocates and frees through its own heap without atomic instructions, and blocks freed on another thread go home in batches, one compare-and-swap per batch. It is faster than mimalloc, jemalloc and snmalloc on [mimalloc-bench](https://github.com/daanx/mimalloc-bench) and on the held-out Rust programs on Linux, and on mimalloc-bench it holds about two thirds of mimalloc's peak memory. A program that wants its memory resident for its whole run can back or pin the whole region before its first allocation with [`Commit::Populate`](https://docs.rs/bcmalloc/latest/bcmalloc/enum.Commit.html#variant.Populate) or [`Commit::Lock`](https://docs.rs/bcmalloc/latest/bcmalloc/enum.Commit.html#variant.Lock). [DESIGN.md](https://github.com/clabby/bcmalloc/blob/main/DESIGN.md) explains how it works, and [BENCHMARKS.md](https://github.com/clabby/bcmalloc/blob/main/BENCHMARKS.md) has every measurement.

Declare it as the global allocator, and the region is reserved the first time anything allocates.

Expand Down Expand Up @@ -111,7 +111,8 @@ The development suite has 51 synthetic workloads and is what the allocator is tu
- 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 64 KiB are refused, and the allocation fails.
- A thread that finds all `max_heaps` heaps taken fails its allocations.
- 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). Idle memory goes back under `Commit::Populate` too, and faults in again when it is reused.
- 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.
- The minimum supported Rust version is 1.88. The `allocator-api` feature needs 1.100, where the standard library's `Allocator` trait became stable.

Expand Down
122 changes: 85 additions & 37 deletions crates/bcmalloc/src/chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,43 +322,54 @@ impl<'a> Chunks<'a> {
/// Claims every free chunk one word at a time, hands each maximal free run to `visit`, records
/// that the runs were purged, and gives the chunks back.
///
/// The caller returns the runs' pages to the OS in `visit`, which is why they count as purged.
/// While `visit` runs the run belongs to the caller, so nobody can allocate and use it at the
/// same time. The cost is that other threads see up to 64 chunks of free memory as missing
/// while a word is being drained.
pub(crate) fn drain(&self, mut visit: impl FnMut(Range<usize>)) {
/// The caller returns the runs' pages to the OS in `visit` and returns whether that worked. A
/// run whose pages went back counts as purged, and one whose pages stayed keeps its state, so a
/// dirty chunk is not taken for zeros. While `visit` runs the run belongs to the caller, so
/// nobody can allocate and use it at the same time. The cost is that other threads see up to 64
/// chunks of free memory as missing while a word is being drained.
pub(crate) fn drain(&self, mut visit: impl FnMut(Range<usize>) -> bool) {
for (w, word) in self.used.iter().take(Self::words_for(self.len)).enumerate() {
let valid = self.valid_mask(w);
let claimed = !word.fetch_or(valid, Ordering::AcqRel) & valid;
let mut rest = claimed;
while rest != 0 {
let start = rest.trailing_zeros() as usize;
let run = (rest >> start).trailing_ones() as usize;
visit(w * WORD + start..w * WORD + start + run);
rest &= !run_mask(run, start);
}
let purged = Self::visit_runs(w, claimed, &mut visit);
if claimed != 0 {
self.purged[w].fetch_or(claimed, Ordering::Relaxed);
self.dirty[w].fetch_and(!claimed, Ordering::Relaxed);
self.purged[w].fetch_or(purged, Ordering::Relaxed);
self.dirty[w].fetch_and(!purged, Ordering::Relaxed);
word.fetch_and(!claimed, Ordering::Release);
}
}
}

/// Hands each maximal run of the chunks of word `w` set in `claimed` to `visit`, and returns
/// the chunks of the runs for which it returned true.
fn visit_runs(w: usize, claimed: u64, visit: &mut impl FnMut(Range<usize>) -> bool) -> u64 {
let (mut rest, mut done) = (claimed, 0);
while rest != 0 {
let start = rest.trailing_zeros() as usize;
let run = (rest >> start).trailing_ones() as usize;
let mask = run_mask(run, start);
if visit(w * WORD + start..w * WORD + start + run) {
done |= mask;
}
rest &= !mask;
}
done
}

/// One pass of the purge clock at time `now` in milliseconds. Free granules with a dirty chunk,
/// in a word whose latest free is at least `delay` old, are claimed and handed to `visit` in
/// maximal runs. Returns whether such granules remain because their word was freed into too
/// recently. Dirty chunks in a granule that is partly in use wait until it is wholly free.
///
/// Only chunks that this pass has claimed are visited, so `visit` may return their pages to the
/// OS without risk to a live allocation. The claims are release operations, so a thread that
/// sees a chunk missing because of this pass also sees anything the caller stored before the
/// pass began.
/// OS without risk to a live allocation. It returns whether that worked, as for
/// [`drain`](Self::drain). The claims are release operations, so a thread that sees a chunk
/// missing because of this pass also sees anything the caller stored before the pass began.
pub(crate) fn purge_pass(
&self,
now: u64,
delay: u64,
mut visit: impl FnMut(Range<usize>),
mut visit: impl FnMut(Range<usize>) -> bool,
) -> bool {
let mut pending = false;
for w in 0..Self::words_for(self.len) {
Expand Down Expand Up @@ -392,16 +403,10 @@ impl<'a> Chunks<'a> {
Err(actual) => seen = actual,
}
};
let mut rest = claimed;
while rest != 0 {
let start = rest.trailing_zeros() as usize;
let run = (rest >> start).trailing_ones() as usize;
visit(w * WORD + start..w * WORD + start + run);
rest &= !run_mask(run, start);
}
let purged = Self::visit_runs(w, claimed, &mut visit);
if claimed != 0 {
self.purged[w].fetch_or(claimed, Ordering::Relaxed);
self.dirty[w].fetch_and(!claimed, Ordering::Relaxed);
self.purged[w].fetch_or(purged, Ordering::Relaxed);
self.dirty[w].fetch_and(!purged, Ordering::Relaxed);
self.used[w].fetch_and(!claimed, Ordering::Release);
}
}
Expand Down Expand Up @@ -708,7 +713,10 @@ mod test {
chunks.free_at(first, 4, 100);
assert!(chunks.purge_pass(105, 10, |_| panic!("too early")), "the chunks are waiting");
let mut purged = Vec::new();
assert!(!chunks.purge_pass(110, 10, |run| purged.push(run)));
assert!(!chunks.purge_pass(110, 10, |run| {
purged.push(run);
true
}));
assert_eq!(purged.len(), 1);
assert_eq!(purged[0], first..first + 4);
assert_eq!(chunks.free_chunks(), 8, "purging gives the chunks back");
Expand All @@ -725,7 +733,10 @@ mod test {
chunks.free_at(b, 1, 108);
chunks.purge_pass(112, 10, |_| panic!("the word was freed into at 108"));
let mut purged = Vec::new();
chunks.purge_pass(118, 10, |run| purged.push(run));
chunks.purge_pass(118, 10, |run| {
purged.push(run);
true
});
assert_eq!(purged.len(), 1);
assert_eq!(purged[0], a..b + 1);
}
Expand All @@ -740,17 +751,34 @@ mod test {
chunks.purge_pass(1000, 10, |_| panic!("the chunk is in use"));
chunks.free_at(first, 1, 1000);
let mut purged = Vec::new();
chunks.purge_pass(1010, 10, |run| purged.push(run));
chunks.purge_pass(1010, 10, |run| {
purged.push(run);
true
});
assert_eq!(purged.len(), 1);
}

#[test]
fn a_run_whose_pages_stayed_is_not_taken_for_zeros() {
let bitmap = Bitmap::new(8);
let chunks = bitmap.chunks();
let first = chunks.alloc(4, 1, 0).unwrap();
chunks.free_at(first, 4, 100);
// The kernel refused to take the pages back, as it does for pages locked in memory.
chunks.purge_pass(1000, 10, |_| false);
chunks.drain(|_| false);
assert_eq!(chunks.alloc(4, 1, 0), Some(first), "the chunks are free again");
assert!(!chunks.is_clean(first, 4, true), "the chunks still hold what was written");
chunks.take_purged(first, 4, |_| panic!("nothing was given back"));
}

#[test]
fn claiming_purged_chunks_reports_each_run_once() {
let bitmap = Bitmap::new(8);
let chunks = bitmap.chunks();
let first = chunks.alloc(8, 1, 0).unwrap();
chunks.free_at(first, 8, 0);
chunks.purge_pass(10, 10, |_| ());
chunks.purge_pass(10, 10, |_| true);
assert_eq!(chunks.alloc(3, 1, 0), Some(5), "runs of several chunks come from the top");
let mut reported = Vec::new();
chunks.take_purged(5, 3, |run| reported.push(run));
Expand Down Expand Up @@ -793,6 +821,7 @@ mod test {
assert!(!visited[chunk], "chunk {chunk} visited twice");
visited[chunk] = true;
}
true
});

let expected: Vec<_> =
Expand Down Expand Up @@ -857,12 +886,18 @@ mod test {
chunks.free_at(chunk, 1, 0);
}
let mut purged = Vec::new();
assert!(!chunks.purge_pass(100, 10, |run| purged.push(run)));
assert!(!chunks.purge_pass(100, 10, |run| {
purged.push(run);
true
}));
assert_eq!(purged.len(), 1, "only the wholly free huge page goes back");
assert_eq!(purged[0], 32..64);
chunks.free_at(0, 1, 100);
purged.clear();
chunks.purge_pass(200, 10, |run| purged.push(run));
chunks.purge_pass(200, 10, |run| {
purged.push(run);
true
});
assert_eq!(purged.first(), Some(&(0..32)));
}
#[test]
Expand All @@ -876,7 +911,7 @@ mod test {
assert_eq!(again, first);
assert!(!chunks.is_clean(first, 4, true), "used since it was fresh");
chunks.free_at(first, 4, 0);
chunks.purge_pass(100, 10, |_| ());
chunks.purge_pass(100, 10, |_| true);
assert!(chunks.claim_at(first, 4));
assert!(chunks.is_clean(first, 4, true), "purged pages that read as zeros");
assert!(!chunks.is_clean(first, 4, false), "purged pages that may keep their contents");
Expand All @@ -893,7 +928,10 @@ mod test {
chunks.free_at(first + 1, 1, 0);
}
let mut purged = Vec::new();
chunks.purge_pass(100, 10, |run| purged.push(run));
chunks.purge_pass(100, 10, |run| {
purged.push(run);
true
});
assert_eq!(purged, vec![(1..2)], "small pages go one chunk at a time, huge pages whole");
}
#[test]
Expand All @@ -905,10 +943,19 @@ mod test {
chunks.free_at(first, 32, 0);
}
let mut purged = Vec::new();
assert!(chunks.purge_pass(20, 10, |run| purged.push(run)), "the huge page still waits");
assert!(
chunks.purge_pass(20, 10, |run| {
purged.push(run);
true
}),
"the huge page still waits"
);
assert_eq!(purged, vec![(0..32)]);
purged.clear();
assert!(!chunks.purge_pass(100, 10, |run| purged.push(run)));
assert!(!chunks.purge_pass(100, 10, |run| {
purged.push(run);
true
}));
assert_eq!(purged, vec![(128..160)]);
}

Expand Down Expand Up @@ -1019,6 +1066,7 @@ mod loom_test {
for chunk in run {
assert!(!held[chunk].load(Ordering::SeqCst), "purged a chunk in use");
}
true
});
})
};
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 @@ -5,11 +5,13 @@ use crate::chunks::CHUNK_SIZE;
/// How much of the reserved memory is backed by physical pages when the region is created.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Commit {
/// Pages are backed on first use. Start-up is instant and the footprint follows the workload.
/// Pages are backed on first use, and pages that stay idle go back to the operating system.
/// Start-up is instant and the footprint follows the workload.
#[default]
Lazy,
/// Every page is backed before the region is returned, so the allocator never takes a page
/// fault. The whole capacity counts as resident from the start.
/// Every page is backed before the region is returned and stays backed: idle memory is never
/// given back, so the allocator never takes a page fault. The whole capacity counts as
/// resident from the start.
Populate,
/// As `Populate`, and the pages are also pinned in RAM so they are never swapped out. This
/// needs a high enough `RLIMIT_MEMLOCK`, and creating the region fails without it.
Expand Down
Loading
Loading