From 3539a7c99bf6be297839510004609af1e2944ee4 Mon Sep 17 00:00:00 2001 From: clabby Date: Sat, 14 Nov 2026 11:14:01 -0500 Subject: [PATCH] Serve alignments up to 4 MiB with aligned runs of whole chunks An alignment above a chunk, 64 KiB, was refused, so a Rust program that asked for a 2 MiB-aligned buffer aborted and C's posix_memalign returned ENOMEM. Such a request is now a run of whole chunks that starts on a multiple of its alignment, which the chunk bitmap already claims at an alignment of up to one word of 64 chunks, so MAX_ALIGN is 4 MiB. A small request aligned that far takes two chunks, so that every huge block still holds more than MAX_SMALL bytes and the paths that know only a block's size, C's free and realloc among them, still tell it from a block of a slab. The heap's cache of freed runs only hands out a run that is aligned as asked. The fast paths are unchanged. A free with a layout still looks at the size alone, which leaves a small size aligned past a chunk on the path of slab blocks. The chunk map entry of a huge block now marks it with the top bit of the owner rather than of the word, and below that bit it reads as a block of the smallest class owned by a heap that does not exist. The fast free takes it for another heap's block of a class that goes home and calls send, which tells it by the owner and frees it as a huge block. Checking the alignment in the free instead cost the churn workloads 2 to 3%. classify tests the alignment first, as it did against the old limit, and goes out of line past a chunk. The cache of freed runs checks a run's alignment with a mask, because a division there costs the 256 KiB and 1 MiB pair workloads about 5%. __rust_alloc, __rust_dealloc and C's malloc, calloc and free compile to the same instruction sequences on x86-64 as before. --- DESIGN.md | 4 +- README.md | 2 +- crates/bcmalloc/src/allocator.rs | 2 +- crates/bcmalloc/src/global.rs | 3 +- crates/bcmalloc/src/heap.rs | 128 +++++++++++++++++++++++++----- crates/bcmalloc/src/region.rs | 40 ++++++++-- crates/bcmalloc/src/size_class.rs | 65 ++++++++++++--- crates/bcmalloc/src/testing.rs | 7 +- crates/bcmalloc/tests/global.rs | 12 +++ crates/cabi/src/lib.rs | 10 ++- 10 files changed, 222 insertions(+), 51 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 997a28e..508e0dd 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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. @@ -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. diff --git a/README.md b/README.md index 0eb85cb..719e370 100644 --- a/README.md +++ b/README.md @@ -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`. diff --git a/crates/bcmalloc/src/allocator.rs b/crates/bcmalloc/src/allocator.rs index 576e4e8..2c47f69 100644 --- a/crates/bcmalloc/src/allocator.rs +++ b/crates/bcmalloc/src/allocator.rs @@ -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()); } } diff --git a/crates/bcmalloc/src/global.rs b/crates/bcmalloc/src/global.rs index 9897495..4351282 100644 --- a/crates/bcmalloc/src/global.rs +++ b/crates/bcmalloc/src/global.rs @@ -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. diff --git a/crates/bcmalloc/src/heap.rs b/crates/bcmalloc/src/heap.rs index 4c88970..56a3f78 100644 --- a/crates/bcmalloc/src/heap.rs +++ b/crates/bcmalloc/src/heap.rs @@ -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; @@ -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(), } } @@ -800,10 +804,10 @@ 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; } @@ -811,7 +815,7 @@ impl HeapData { // 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 @@ -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. @@ -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 { @@ -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, 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()) }; @@ -1175,7 +1185,7 @@ impl HeapData { unsafe fn free_huge(&self, ptr: NonNull, 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) }; }; @@ -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 /// @@ -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 /// @@ -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() }; @@ -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); @@ -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); @@ -2459,6 +2494,7 @@ impl Drop for Heap<'_> { mod test { use super::*; use crate::{ + MAX_ALIGN, chunks::CHUNK_SIZE, testing::{Harness, Rng, TestRegion, iterations, random_traffic}, }; @@ -2466,6 +2502,7 @@ mod test { alloc::Layout, mem::{MaybeUninit, align_of, offset_of, size_of}, ptr::NonNull, + slice, }; use std::vec::Vec; @@ -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(®ion), 0); + } + #[test] fn huge_allocations_span_chunks_and_release_them() { let test = TestRegion::new(160, 1); @@ -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] diff --git a/crates/bcmalloc/src/region.rs b/crates/bcmalloc/src/region.rs index 4985b9a..7c0d308 100644 --- a/crates/bcmalloc/src/region.rs +++ b/crates/bcmalloc/src/region.rs @@ -196,6 +196,10 @@ impl<'a> Region<'a> { pub(crate) unsafe fn from_parts(parts: Parts<'a>) -> Self { debug_assert_eq!(parts.slabs.len(), parts.chunk_count); debug_assert_eq!(parts.map.len(), parts.chunk_count); + // Heap ids must stay below the bit that marks huge blocks, and a huge block's length in + // 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); 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 @@ -268,7 +272,7 @@ impl<'a> Region<'a> { // SAFETY: the caller gives the block up, and the chunk map names its owner. unsafe { self.heap_slot(owner).post_block(ptr.as_ptr().cast()) }; } - Some(Request::Huge { chunks }) => { + Some(Request::Huge { chunks, .. }) => { #[cfg(feature = "metrics")] { self.counters.huge_frees.add(1); @@ -732,8 +736,9 @@ impl<'a> Region<'a> { /// or for the first chunk of a huge block, how many chunks the block spans. /// /// The owner sits in the low 32 bits, so the free path reads it with one load and a truncation. -/// The top bit marks a huge block. Frees through the Rust interfaces know a huge block by its -/// layout. The entry is what lets a C `free` without a size tell the two apart. +/// The top bit of the owner marks a huge block, and no heap has an id with that bit. Frees through +/// the Rust interfaces know most huge blocks by their size, and C's `free` tells the two apart by +/// the entry. See [`Entry::huge`] for the rest. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Entry(pub(crate) u64); @@ -745,22 +750,29 @@ impl Entry { Self(owner as u64 | (class.index() as u64) << 32 | offset << 40) } - /// The bit that marks the entry of the first chunk of a huge block. - const HUGE: u64 = 1 << 63; + /// The bit of the owner that marks the entry of the first chunk of a huge block. Heap ids stay + /// below it. + pub(crate) const HUGE_OWNER: u32 = 1 << 31; /// The entry for the first chunk of a huge block of `chunks` chunks. + /// + /// Read as a slab's, it is an entry of the smallest class, whose bin comes first, owned by + /// heap `HUGE_OWNER | chunks`, which does not exist. A Rust free of a small size aligned past + /// a chunk, which is a huge block, therefore needs no test of its own: the fast free takes the + /// block for another heap's block of a class that goes home and calls `HeapData::send`, which + /// tells it apart by the owner. pub(crate) const fn huge(chunks: usize) -> Self { - Self(Self::HUGE | chunks as u64) + Self((Self::HUGE_OWNER as usize | chunks) as u64) } /// The number of chunks of a huge block, or None if the entry is a slab's. pub(crate) const fn huge_chunks(self) -> Option { - if self.is_huge() { Some((self.0 & !Self::HUGE) as usize) } else { None } + if self.is_huge() { Some((self.owner() & !Self::HUGE_OWNER) as usize) } else { None } } /// Whether the entry is that of the first chunk of a huge block. pub(crate) const fn is_huge(self) -> bool { - self.0 & Self::HUGE != 0 + self.owner() & Self::HUGE_OWNER != 0 } /// The id of the heap that owns the slab. @@ -1054,6 +1066,18 @@ mod test { }); } + #[test] + fn a_huge_blocks_entry_reads_as_a_block_of_no_heap_that_goes_home() { + for chunks in [2, 64, Entry::HUGE_OWNER as usize - 1] { + let entry = Entry::huge(chunks); + assert_eq!(entry.huge_chunks(), Some(chunks)); + assert!(entry.owner() >= Entry::HUGE_OWNER, "no heap has the owner's id"); + assert_eq!((entry.class().index(), entry.bin_offset()), (0, 0), "the smallest class"); + } + let slab = Entry::new(Entry::HUGE_OWNER - 1, Class::for_size(crate::MAX_SMALL)); + assert_eq!(slab.huge_chunks(), None, "the last heap's slabs are not huge"); + } + #[test] fn a_mapping_backs_a_working_region() { let mapping = Mapping::new(&config(64 * MIB)).unwrap(); diff --git a/crates/bcmalloc/src/size_class.rs b/crates/bcmalloc/src/size_class.rs index 59d329e..6c63ca1 100644 --- a/crates/bcmalloc/src/size_class.rs +++ b/crates/bcmalloc/src/size_class.rs @@ -32,7 +32,8 @@ //! multiple of 8, so every block is 8-byte aligned. A request that asks for 16, 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 that is at least as large as the alignment. Huge allocations start on a -//! chunk boundary, so the largest supported alignment is one chunk. +//! chunk boundary, and a request for more alignment than a chunk is served as a huge allocation +//! that starts on a multiple of its alignment, up to [`MAX_ALIGN`]. use crate::chunks::CHUNK_SIZE; use core::alloc::Layout; @@ -44,8 +45,10 @@ pub(crate) const MIN_ALIGN: usize = 16; /// has. pub(crate) const STEP: usize = 8; -/// The largest alignment the allocator supports, which is one chunk. -pub const MAX_ALIGN: usize = CHUNK_SIZE; +/// The largest alignment the allocator supports, 4 MiB. A block aligned to more than a chunk is a +/// run of whole chunks, and the region aligns its memory to one bitmap word of 64 chunks, the +/// furthest a run can be aligned. +pub const MAX_ALIGN: usize = 64 * CHUNK_SIZE; /// The largest block served from a slab. Bigger requests are huge allocations. pub const MAX_SMALL: usize = 64 << 10; @@ -80,8 +83,15 @@ pub(crate) struct Class(u8); pub(crate) enum Request { /// A block from a slab of this class. Small(Class), - /// A run of this many whole chunks. - Huge { chunks: usize }, + /// A run of this many whole chunks, starting on a multiple of `align` chunks. + Huge { chunks: usize, align: usize }, +} + +/// Whether [`classify`] serves `layout` from a slab: its size and its alignment are both at most +/// a chunk. +#[cfg(any(test, feature = "testing"))] +pub(crate) const fn is_small(layout: Layout) -> bool { + layout.size() <= MAX_SMALL && layout.align() <= CHUNK_SIZE } /// The block size of class index `i`. @@ -304,11 +314,11 @@ impl Class { /// Decides how a layout is served, or `None` if it cannot be (alignment above [`MAX_ALIGN`]). pub(crate) const fn classify(layout: Layout) -> Option { let (size, align) = (layout.size(), layout.align()); - if align > MAX_ALIGN { - return None; + if align > CHUNK_SIZE { + return classify_aligned_run(size, align); } if size > MAX_SMALL { - return Some(Request::Huge { chunks: size.div_ceil(CHUNK_SIZE) }); + return Some(Request::Huge { chunks: size.div_ceil(CHUNK_SIZE), align: 1 }); } // Over-aligned blocks come from power-of-two classes, as the module documentation explains. let size = if align <= STEP { @@ -322,6 +332,21 @@ pub(crate) const fn classify(layout: Layout) -> Option { Some(Request::Small(Class::for_size(size))) } +/// Decides how a request aligned past a chunk is served, out of line because it is rare. +/// +/// Only runs of whole chunks are aligned more than a chunk, so a small request that asks for that +/// takes a run of its own. It takes at least two chunks: every huge block holds more than +/// [`MAX_SMALL`] bytes, which is how the paths that know only a block's size, such as C's realloc, +/// tell it from a block of a slab. +#[cold] +const fn classify_aligned_run(size: usize, align: usize) -> Option { + if align > MAX_ALIGN { + return None; + } + let chunks = size.div_ceil(CHUNK_SIZE); + Some(Request::Huge { chunks: if chunks > 2 { chunks } else { 2 }, align: align / CHUNK_SIZE }) +} + #[cfg(test)] mod test { use super::*; @@ -408,7 +433,7 @@ mod test { #[test] fn blocks_honour_the_requested_alignment() { - for align_shift in 0..=16 { + for align_shift in 0..=MAX_ALIGN.ilog2() { let align = 1usize << align_shift; for size in [1, 7, 16, 100, 4096, 5000, 70_000, MAX_SMALL, MAX_SMALL + 1, 3 << 20] { match classify(layout(size, align)).unwrap() { @@ -418,7 +443,10 @@ mod test { // in, so a block size that is a multiple of the alignment is enough. assert_eq!(class.block_size() % align, 0, "{size}/{align}"); } - Request::Huge { chunks } => assert!(chunks * CHUNK_SIZE >= size), + Request::Huge { chunks, align: run_align } => { + assert!(chunks * CHUNK_SIZE >= size); + assert!(run_align * CHUNK_SIZE >= align, "{size}/{align}"); + } } } } @@ -442,7 +470,7 @@ mod test { classify(layout(MAX_SMALL, 1)), Some(Request::Small(Class::from_index(CLASSES - 1))) ); - assert_eq!(classify(layout(MAX_SMALL + 1, 1)), Some(Request::Huge { chunks: 2 })); + assert_eq!(classify(layout(MAX_SMALL + 1, 1)), Some(Request::Huge { chunks: 2, align: 1 })); assert_eq!( classify(layout(CHUNK_SIZE, 1)), Some(Request::Small(Class::for_size(CHUNK_SIZE))) @@ -450,8 +478,19 @@ mod test { } #[test] - fn alignment_beyond_a_chunk_is_refused() { + fn alignment_beyond_a_chunk_takes_an_aligned_run_up_to_the_limit() { + assert_eq!( + classify(layout(8, 2 * CHUNK_SIZE)), + Some(Request::Huge { chunks: 2, align: 2 }), + "a small request aligned past a chunk takes a run of its own, bigger than a slab block" + ); + assert_eq!(classify(layout(0, MAX_ALIGN)), Some(Request::Huge { chunks: 2, align: 64 })); assert_eq!(classify(layout(8, MAX_ALIGN * 2)), None); - assert!(classify(layout(8, MAX_ALIGN)).is_some()); + for size in [1, MAX_SMALL, MAX_SMALL + 1] { + for align in [1, CHUNK_SIZE, 2 * CHUNK_SIZE, MAX_ALIGN] { + let small = matches!(classify(layout(size, align)), Some(Request::Small(_))); + assert_eq!(is_small(layout(size, align)), small, "{size}/{align}"); + } + } } } diff --git a/crates/bcmalloc/src/testing.rs b/crates/bcmalloc/src/testing.rs index 8e2539a..5b421ed 100644 --- a/crates/bcmalloc/src/testing.rs +++ b/crates/bcmalloc/src/testing.rs @@ -364,7 +364,7 @@ impl<'r> Harness<'r> { } // Huge blocks are runs of chunks and not blocks of a slab. for block in &self.live { - if block.layout.size() > crate::MAX_SMALL { + if !crate::size_class::is_small(block.layout) { seen.remove(&block.ptr.as_ptr().addr()); } } @@ -466,7 +466,8 @@ pub fn random_traffic(region: &Region<'_>, seed: u64, steps: usize) { let heap = rng.below(3); match rng.below(23) { 0..=9 => { - let widest = if rng.below(8) == 0 { 17 } else { 5 }; + let widest = + if rng.below(8) == 0 { crate::MAX_ALIGN.ilog2() as usize + 2 } else { 5 }; let align = 1 << rng.below(widest); if rng.below(4) == 0 { harness.alloc_zeroed(heap, random_size(&mut rng), align); @@ -517,7 +518,7 @@ fn interpret(harness: &mut Harness<'_>, bytes: &mut impl Iterator) 0..=7 => { let limit = [256, 4 << 10, 600 << 10, 6 << 20][bytes.next()? % 4]; let size = (bytes.next()? | bytes.next()? << 8 | bytes.next()? << 16) % limit + 1; - let align = 1 << (bytes.next()? % 18); + let align = 1 << (bytes.next()? % 24); if op % 16 < 6 { harness.alloc(heap, size, align); } else { diff --git a/crates/bcmalloc/tests/global.rs b/crates/bcmalloc/tests/global.rs index 1f47707..5e4dabf 100644 --- a/crates/bcmalloc/tests/global.rs +++ b/crates/bcmalloc/tests/global.rs @@ -65,6 +65,18 @@ fn over_aligned_types_are_aligned() { let chunk = Box::new(Chunk([3; 100])); assert_eq!(std::ptr::from_ref(&*chunk).addr() % 65536, 0); assert_eq!(chunk.0[99], 3); + // Past a chunk, an alignment takes a run of whole chunks that starts on it. + for align in [128 << 10, 2 << 20, 4 << 20] { + let layout = std::alloc::Layout::from_size_align(100, align).unwrap(); + // SAFETY: the layout has a non-zero size. + let block = unsafe { std::alloc::alloc(layout) }; + assert!(!block.is_null() && block.addr() % align == 0, "aligned to {align}"); + // SAFETY: the block holds 100 bytes, and is freed once with its layout. + unsafe { + block.write_bytes(5, 100); + std::alloc::dealloc(block, layout); + } + } assert_eq!(0u128.to_ne_bytes().len(), 16); } diff --git a/crates/cabi/src/lib.rs b/crates/cabi/src/lib.rs index c47f26a..e700539 100644 --- a/crates/cabi/src/lib.rs +++ b/crates/cabi/src/lib.rs @@ -349,12 +349,20 @@ mod test { let mut out = ptr::dangling_mut::(); set_errno(7); assert_eq!(posix_memalign(&raw mut out, 4, 100), libc::EINVAL); - assert_eq!(posix_memalign(&raw mut out, 1 << 20, 100), libc::ENOMEM); + assert_eq!(posix_memalign(&raw mut out, 8 << 20, 100), libc::ENOMEM); assert_eq!(out, ptr::dangling_mut(), "a failed call leaves the output alone"); assert_eq!(errno(), 7, "and errno too"); assert_eq!(posix_memalign(&raw mut out, 4096, 100), 0); assert!(out.addr().is_multiple_of(4096)); free(out); + // An alignment past a chunk takes a run of whole chunks that starts on it, which C's + // realloc and free handle without knowing the alignment. + assert_eq!(posix_memalign(&raw mut out, 2 << 20, 100), 0); + assert!(out.addr().is_multiple_of(2 << 20)); + out.cast::().write_bytes(6, 100); + let moved = realloc(out, 300 << 10); + assert!(!moved.is_null() && moved.cast::().add(99).read() == 6); + free(moved); let page = page_size(); let block = pvalloc(1); assert!(block.addr().is_multiple_of(page) && malloc_usable_size(block) >= page);