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: 2 additions & 2 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ Each class is carved out of slabs, which are runs of chunks aligned to their own
| 16 B to 8 KiB | 64 KiB (1) | 8 to 4096 |
| 8 KiB to 64 KiB | 512 KiB (8) | 8 to 56 |

Alignment falls out of the geometry. A slab starts on a multiple of its own size and a block on a multiple of its size within the slab, so a block is aligned to the largest power of two that divides its size, and at least to 8 bytes. A request that asks for 16 bytes of alignment, which C's malloc always does, is rounded up to a multiple of 16 first. A request for more alignment is rounded up to a power of two at least that large. The largest alignment supported is one chunk, 64 KiB.
Alignment falls out of the geometry. A slab starts on a multiple of its own size and a block on a multiple of its size within the slab, so a block is aligned to the largest power of two that divides its size, and at least to 8 bytes. A request that asks for 16 bytes of alignment, which C's malloc always does, is rounded up to a multiple of 16 first. A request for more alignment is rounded up to a power of two at least that large. A request for more alignment than a chunk gets a run of whole chunks that starts on a multiple of its alignment. The run is at least two chunks long, so that a huge block always holds more than 64 KiB and a free that knows only the size, as C's does, tells it from a block of a slab. A run can be aligned to at most one bitmap word of 64 chunks, so the largest alignment supported is 4 MiB.

Anything above 64 KiB gets a run of whole chunks to itself, as jemalloc gives large requests extents of their own[^jemalloc]. A slab of such blocks would hold so few of them that one partly used slab per class and heap would cost more than rounding up to whole chunks does.

Expand Down Expand Up @@ -260,7 +260,7 @@ These are the costs.

## 14. Limits

- Alignments above 64 KiB are refused.
- 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.
- 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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,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 64 KiB are refused, and the allocation fails.
- 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.
- 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`.
Expand Down
2 changes: 1 addition & 1 deletion crates/bcmalloc/src/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,6 @@ mod test {
let test = TestRegion::new(8, 1);
let region = test.region();
let heap = region.heap().unwrap();
assert!(heap.allocate(layout(8, 1 << 20)).is_err());
assert!(heap.allocate(layout(8, 2 * crate::MAX_ALIGN)).is_err());
}
}
3 changes: 2 additions & 1 deletion crates/bcmalloc/src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,10 +599,11 @@ unsafe impl GlobalAlloc for Bcmalloc {
// SAFETY: the caller guarantees the block came from this allocator with this layout.
return unsafe { self.dealloc_unbound(ptr, layout) };
};
// A small size aligned past a chunk is a huge block, which the chunk map entry tells.
if layout.size() <= MAX_SMALL {
// SAFETY: a thread's bound heap is claimed by that thread alone, it published the
// directory when it bound the heap, and the caller guarantees the block came from
// this allocator with this layout, so it is a block of a slab in the region.
// this allocator with this layout, so it is a block in the region.
unsafe { data.free_entry(ptr.as_ptr().cast(), self.directory.entry(ptr.as_ptr())) };
} else {
// SAFETY: as above.
Expand Down
128 changes: 107 additions & 21 deletions crates/bcmalloc/src/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ const fn reusable_anywhere(class: Class) -> bool {
class.reusable_anywhere() || class.index() == MESSAGE_CLASS.index()
}

// The fast free sends a huge block whose entry it reads as one of the smallest class to
// `HeapData::send` only because blocks of that class go home. See `Entry::huge`.
const _: () = assert!(!reusable_anywhere(Class::from_index(0)));

/// How many blocks a bin that overflows gives back at a time, from a buffer on the stack.
const FLUSH_BATCH: usize = 512;

Expand Down Expand Up @@ -788,7 +792,7 @@ impl HeapData {
.cast()
}
// SAFETY: forwarded.
Some(Request::Huge { chunks }) => unsafe { self.alloc_whole(chunks) },
Some(Request::Huge { chunks, align }) => unsafe { self.alloc_whole(chunks, align) },
None => ptr::null_mut(),
}
}
Expand All @@ -800,18 +804,18 @@ impl HeapData {
///
/// The caller must hold the claim on this slot.
#[inline(never)]
unsafe fn alloc_whole(&self, chunks: usize) -> *mut u8 {
unsafe fn alloc_whole(&self, chunks: usize, align: usize) -> *mut u8 {
// SAFETY: the claim keeps the region alive.
let region = unsafe { self.region() };
let block = self.alloc_huge(region, chunks);
let block = self.alloc_huge(region, chunks, align);
if !block.is_null() {
return block;
}
// The region looks full, but this heap may be sitting on empty slabs. Give them back and
// retry.
// SAFETY: the caller holds the claim.
unsafe { self.flush(region) };
self.alloc_huge(region, chunks)
self.alloc_huge(region, chunks, align)
}

/// Fills the empty bin of `class` and pops a block, or returns null if the region is out of
Expand Down Expand Up @@ -1020,14 +1024,14 @@ impl HeapData {
}
block
}
Some(Request::Huge { chunks }) => {
Some(Request::Huge { chunks, align }) => {
// SAFETY: the claim keeps the region alive.
let region = unsafe { self.region() };
let (mut block, mut zeroed) = self.alloc_huge_zeroed(region, chunks);
let (mut block, mut zeroed) = self.alloc_huge_zeroed(region, chunks, align);
if block.is_null() {
// SAFETY: the caller holds the claim.
unsafe { self.flush(region) };
(block, zeroed) = self.alloc_huge_zeroed(region, chunks);
(block, zeroed) = self.alloc_huge_zeroed(region, chunks, align);
}
if !block.is_null() && !zeroed {
// SAFETY: as above.
Expand Down Expand Up @@ -1114,7 +1118,12 @@ impl HeapData {
return ptr.as_ptr();
}
}
(Some(Request::Huge { chunks: had }), Some(Request::Huge { chunks: wants })) => {
// A huge block grows and shrinks in place from where it starts, which keeps its
// alignment.
(
Some(Request::Huge { chunks: had, .. }),
Some(Request::Huge { chunks: wants, .. }),
) => {
let first = region.chunk_index(ptr.as_ptr());
if wants <= had {
if wants < had {
Expand Down Expand Up @@ -1154,6 +1163,7 @@ impl HeapData {
/// this region with exactly the layout and not be used again.
#[inline(always)]
pub(crate) unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
// A small size aligned past a chunk is a huge block, which the chunk map entry tells.
if layout.size() <= MAX_SMALL {
// SAFETY: forwarded.
unsafe { self.free_small(ptr.as_ptr().cast()) };
Expand All @@ -1175,7 +1185,7 @@ impl HeapData {
unsafe fn free_huge(&self, ptr: NonNull<u8>, layout: Layout) {
// SAFETY: the claim keeps the region alive.
let region = unsafe { self.region() };
let Some(Request::Huge { chunks }) = classify(layout) else {
let Some(Request::Huge { chunks, .. }) = classify(layout) else {
// SAFETY: forwarded.
return unsafe { region.dealloc(ptr, layout) };
};
Expand All @@ -1201,9 +1211,10 @@ impl HeapData {
region.purge_if_due();
}

/// Frees a block of a slab. Its class and its owner both come from one load of the chunk map,
/// so the layout does not matter beyond telling slab blocks from huge ones, and a block that a
/// realloc kept in place is freed as what it is.
/// Frees a block of at most [`MAX_SMALL`] bytes, which is a block of a slab unless it was
/// aligned past a chunk. Its class and its owner both come from one load of the chunk map, so
/// the layout does not matter beyond its size, a block that a realloc kept in place is freed as
/// what it is, and the entry of a huge block sends it on to be freed as one.
///
/// # Safety
///
Expand Down Expand Up @@ -1263,7 +1274,9 @@ impl HeapData {
Some(entry.huge_chunks().map_or_else(|| entry.class().block_size(), |n| n << CHUNK_SHIFT))
}

/// Frees a block of a slab whose chunk map entry is `entry`.
/// Frees a block of a slab whose chunk map entry is `entry`, or a huge block of a small size
/// aligned past a chunk, whose entry reads as a block of a heap that does not exist and so goes
/// to [`send`](Self::send). See [`Entry::huge`].
///
/// # Safety
///
Expand Down Expand Up @@ -1485,6 +1498,21 @@ impl HeapData {
#[cold]
#[inline(never)]
unsafe fn send(&self, block: *mut Block, class: Class, owner: u32) {
if owner & Entry::HUGE_OWNER != 0 {
// A huge block of a small size aligned past a chunk, freed with its layout. Its entry
// reads as a block of the smallest class that belongs to no heap, so the fast free
// sent it here and counted it as a free of that class. See `Entry::huge`.
#[cfg(feature = "metrics")]
self.bin(class).frees.sub(1);
let chunks = (owner & !Entry::HUGE_OWNER) as usize;
// SAFETY: a huge block of `chunks` chunks has this layout, and the caller gives it up.
return unsafe {
self.free_huge(
NonNull::new_unchecked(block.cast()),
Layout::from_size_align_unchecked(chunks << CHUNK_SHIFT, 16),
)
};
}
count!(self, BlocksSent, 1);
// SAFETY: the claim keeps the region alive.
let region = unsafe { self.region() };
Expand Down Expand Up @@ -2014,16 +2042,23 @@ impl HeapData {
}
}

/// Allocates a run of `chunks` whole chunks, returning null if there is no room.
pub(crate) fn alloc_huge(&self, region: &Region<'_>, chunks: usize) -> *mut u8 {
self.alloc_huge_zeroed(region, chunks).0
/// Allocates a run of `chunks` whole chunks that starts on a multiple of `align` chunks, at
/// most 64, returning null if there is no room.
pub(crate) fn alloc_huge(&self, region: &Region<'_>, chunks: usize, align: usize) -> *mut u8 {
self.alloc_huge_zeroed(region, chunks, align).0
}

/// As [`alloc_huge`](Self::alloc_huge), and also tells whether the block reads as zeros.
fn alloc_huge_zeroed(&self, region: &Region<'_>, chunks: usize) -> (*mut u8, bool) {
fn alloc_huge_zeroed(
&self,
region: &Region<'_>,
chunks: usize,
align: usize,
) -> (*mut u8, bool) {
for kept in &self.private.kept {
let block = kept.get();
if block.chunks == chunks {
// The alignment is a power of two, and a mask saves a division on every reuse.
if block.chunks == chunks && block.first & (align - 1) == 0 {
kept.set(Kept::NONE);
// The next kept block of this size has been asked for, so it stays a while.
self.mark_kept_reused(chunks);
Expand All @@ -2037,7 +2072,7 @@ impl HeapData {
// a huge page or more is worth it whatever the size of the heap.
let huge = chunks >= HUGE_PAGE_CHUNKS || self.is_big();
let part = region.part(self.private.node.get(), huge);
let Some((first, zeroed)) = region.alloc_chunks_zeroed(chunks, 1, 0, part) else {
let Some((first, zeroed)) = region.alloc_chunks_zeroed(chunks, align, 0, part) else {
return (ptr::null_mut(), false);
};
self.note_huge_alloc(chunks);
Expand Down Expand Up @@ -2459,13 +2494,15 @@ impl Drop for Heap<'_> {
mod test {
use super::*;
use crate::{
MAX_ALIGN,
chunks::CHUNK_SIZE,
testing::{Harness, Rng, TestRegion, iterations, random_traffic},
};
use core::{
alloc::Layout,
mem::{MaybeUninit, align_of, offset_of, size_of},
ptr::NonNull,
slice,
};
use std::vec::Vec;

Expand Down Expand Up @@ -2697,6 +2734,55 @@ mod test {
heap.validate();
}

#[test]
fn blocks_aligned_past_a_chunk_are_runs_that_start_on_their_alignment() {
let test = TestRegion::new(320, 1);
let region = test.region();
let heap = region.heap().unwrap();
// A freed run of two chunks that is not 2 MiB aligned stays in the heap's cache, where a
// request of the same size that asks for 2 MiB must not take it.
let loose = layout(2 * CHUNK_SIZE, 8);
let kept = heap.alloc(loose).unwrap();
assert!(!kept.as_ptr().addr().is_multiple_of(2 << 20));
// SAFETY: the block is live with this layout.
unsafe { heap.dealloc(kept, loose) };
for align in [2 * CHUNK_SIZE, 2 << 20, MAX_ALIGN] {
for size in [8, CHUNK_SIZE, 2 * CHUNK_SIZE] {
let layout = layout(size, align);
let block = heap.alloc(layout).unwrap();
assert!(block.as_ptr().addr().is_multiple_of(align), "{size} aligned to {align}");
// SAFETY: the block holds `size` bytes.
unsafe { block.as_ptr().write_bytes(1, size) };
let grown_size = size + 3 * CHUNK_SIZE;
// SAFETY: the block is live with this layout, and the new size is valid.
let grown = unsafe { heap.realloc(block, layout, grown_size) }.unwrap();
assert!(grown.as_ptr().addr().is_multiple_of(align), "a resize kept the alignment");
// A few bytes stand for all of them, which Miri would read one at a time.
for at in [0, size / 2, size - 1] {
// SAFETY: the block holds at least `size` bytes.
assert_eq!(unsafe { grown.as_ptr().add(at).read() }, 1, "byte {at} moved");
}
// SAFETY: the block is live with the grown layout.
unsafe { heap.dealloc(grown, Layout::from_size_align(grown_size, align).unwrap()) };
}
let zeroed = heap.alloc_zeroed(layout(100, align)).unwrap();
assert!(zeroed.as_ptr().addr().is_multiple_of(align));
// SAFETY: the block holds 100 bytes.
assert!(unsafe { slice::from_raw_parts(zeroed.as_ptr(), 100) }.iter().all(|&b| b == 0));
// SAFETY: the block is live with this layout.
unsafe { heap.dealloc(zeroed, layout(100, align)) };
}
// A free without a layout, as C's free does, tells the block from a slab block by its size.
let block = heap.alloc(layout(100, 2 << 20)).unwrap();
assert!(heap.data.usable_size(block).unwrap() > crate::MAX_SMALL);
// SAFETY: the block is live and not used again.
unsafe { heap.free_unsized(block) };
assert_eq!(heap.alloc(layout(8, MAX_ALIGN * 2)), None, "the limit is one bitmap word");
heap.validate();
heap.flush();
assert_eq!(used(&region), 0);
}

#[test]
fn huge_allocations_span_chunks_and_release_them() {
let test = TestRegion::new(160, 1);
Expand Down Expand Up @@ -3260,8 +3346,8 @@ mod test {
let test = TestRegion::new(16, 1);
let region = test.region();
let heap = region.heap().unwrap();
assert!(heap.alloc(layout(8, 2 * CHUNK_SIZE)).is_none());
assert!(heap.alloc(layout(8, CHUNK_SIZE)).is_some());
assert!(heap.alloc(layout(8, 2 * MAX_ALIGN)).is_none());
assert!(heap.alloc(layout(8, MAX_ALIGN)).is_some());
}

#[test]
Expand Down
Loading
Loading