diff --git a/DESIGN.md b/DESIGN.md
index cb55422..997a28e 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -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
@@ -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`.
diff --git a/README.md b/README.md
index f30438f..0eb85cb 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
-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.
@@ -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.
diff --git a/crates/bcmalloc/src/chunks.rs b/crates/bcmalloc/src/chunks.rs
index a6ceca2..b5397cb 100644
--- a/crates/bcmalloc/src/chunks.rs
+++ b/crates/bcmalloc/src/chunks.rs
@@ -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)) {
+ /// 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) -> 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) -> 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),
+ mut visit: impl FnMut(Range) -> bool,
) -> bool {
let mut pending = false;
for w in 0..Self::words_for(self.len) {
@@ -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);
}
}
@@ -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");
@@ -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);
}
@@ -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));
@@ -793,6 +821,7 @@ mod test {
assert!(!visited[chunk], "chunk {chunk} visited twice");
visited[chunk] = true;
}
+ true
});
let expected: Vec<_> =
@@ -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]
@@ -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");
@@ -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]
@@ -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)]);
}
@@ -1019,6 +1066,7 @@ mod loom_test {
for chunk in run {
assert!(!held[chunk].load(Ordering::SeqCst), "purged a chunk in use");
}
+ true
});
})
};
diff --git a/crates/bcmalloc/src/config.rs b/crates/bcmalloc/src/config.rs
index abbcab7..7a651f7 100644
--- a/crates/bcmalloc/src/config.rs
+++ b/crates/bcmalloc/src/config.rs
@@ -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.
diff --git a/crates/bcmalloc/src/region.rs b/crates/bcmalloc/src/region.rs
index ea8ab57..4985b9a 100644
--- a/crates/bcmalloc/src/region.rs
+++ b/crates/bcmalloc/src/region.rs
@@ -138,6 +138,10 @@ struct Clock {
purges_active: AtomicUsize,
/// How many purge passes and trims have finished.
purges_done: AtomicUsize,
+ /// Set when the region keeps every page it has backed: from the start in a region backed up
+ /// front, and from the first time the kernel refuses to take pages back, as it does for pages
+ /// that the program locked in memory. The purge clock then stops, and `trim` leaves pages.
+ keeps_pages: AtomicBool,
}
/// How many chunks slabs and blocks of whole chunks hold, which tells a big process from a small
@@ -222,6 +226,7 @@ impl<'a> Region<'a> {
aging: AtomicBool::new(false),
purges_active: AtomicUsize::new(0),
purges_done: AtomicUsize::new(0),
+ keeps_pages: AtomicBool::new(false),
},
occupancy: Occupancy { _line: [], chunks: AtomicUsize::new(0) },
#[cfg(feature = "metrics")]
@@ -277,7 +282,9 @@ impl<'a> Region<'a> {
}
/// Returns the empty slabs of every idle heap to the region, and tells the operating system
- /// that free chunks no longer need physical pages.
+ /// that free chunks no longer need physical pages. A region that keeps its pages, because it
+ /// was backed up front with [`Commit::Populate`] or [`Commit::Lock`] or because the kernel
+ /// refused to take pages back, only does the first.
///
/// Heaps that are in use are skipped, and a thread trims its own slabs with [`Heap::flush`].
/// While this drains a bitmap word the 64 chunks in it look allocated to everyone else, so run
@@ -299,14 +306,12 @@ impl<'a> Region<'a> {
break;
}
}
+ if self.clock.keeps_pages.load(Ordering::Relaxed) {
+ return;
+ }
self.clock.purges_active.fetch_add(1, Ordering::Release);
- self.chunks.drain(|run| {
- // SAFETY: the run is free and held by the drain while we advise on it.
- unsafe {
- let start = NonNull::new_unchecked(self.chunk_ptr(run.start));
- sys::discard(start, run.len() << CHUNK_SHIFT);
- }
- });
+ // The drain holds each run while its pages go back.
+ self.chunks.drain(|run| self.give_back(run));
self.clock.purges_done.fetch_add(1, Ordering::Release);
self.clock.purges_active.fetch_sub(1, Ordering::Release);
}
@@ -539,15 +544,40 @@ impl<'a> Region<'a> {
}
}
- /// Frees chunks as `Chunks`::free_at does, and starts them ageing towards a purge.
+ /// Frees chunks as `Chunks`::free_at does, and starts them ageing towards a purge unless the
+ /// region keeps its pages.
pub(crate) fn free_chunks(&self, first: usize, n: usize) {
self.occupancy.chunks.fetch_sub(n, Ordering::Relaxed);
self.chunks.free_at(first, n, sys::monotonic_ms());
+ if self.clock.keeps_pages.load(Ordering::Relaxed) {
+ return;
+ }
// A read-modify-write, so that the pass that consumes the flag also sees the bits above no
// matter which free it read the flag from.
self.clock.aging.fetch_or(true, Ordering::Release);
}
+ /// Gives the pages of a run of chunks that a purge pass or a trim holds back to the operating
+ /// system, and returns whether they went. The first refusal, which comes from pages that are
+ /// locked in memory, makes the region keep its pages from then on, since retrying would only
+ /// be refused again.
+ fn give_back(&self, run: Range) -> bool {
+ if self.clock.keeps_pages.load(Ordering::Relaxed) {
+ return false;
+ }
+ // SAFETY: the caller holds the run, so no allocation overlaps it.
+ let given = unsafe {
+ sys::discard(
+ NonNull::new_unchecked(self.chunk_ptr(run.start)),
+ run.len() << CHUNK_SHIFT,
+ )
+ };
+ if !given {
+ self.clock.keeps_pages.store(true, Ordering::Relaxed);
+ }
+ given
+ }
+
/// Runs the purge clock if free chunks are ageing and an interval has passed. Chunks that stay
/// free for one to two intervals go back to the OS. This is called from paths that are already
/// slow, so that an idle program pays nothing and a busy one pays a clock read now and then.
@@ -560,6 +590,11 @@ impl<'a> Region<'a> {
#[cold]
fn purge_when_due(&self) {
+ if self.clock.keeps_pages.load(Ordering::Relaxed) {
+ // Frees no longer set the flag, so this runs at most once after the pages are kept.
+ self.clock.aging.store(false, Ordering::Relaxed);
+ return;
+ }
let now = sys::monotonic_ms();
let due = self.clock.next_purge.load(Ordering::Relaxed);
let won = now >= due &&
@@ -587,14 +622,11 @@ impl<'a> Region<'a> {
self.counters.purge_passes.add(1);
let pending = self.chunks.purge_pass(now, PURGE_INTERVAL_MS, |run| {
#[cfg(feature = "metrics")]
- self.counters.chunks_purged.add(run.len() as u64);
- // SAFETY: the pass holds the run, so no allocation overlaps it.
- unsafe {
- sys::discard(
- NonNull::new_unchecked(self.chunk_ptr(run.start)),
- run.len() << CHUNK_SHIFT,
- );
- }
+ let len = run.len() as u64;
+ let given = self.give_back(run);
+ #[cfg(feature = "metrics")]
+ self.counters.chunks_purged.add(if given { len } else { 0 });
+ given
});
self.clock.purges_done.fetch_add(1, Ordering::Release);
self.clock.purges_active.fetch_sub(1, Ordering::Release);
@@ -916,6 +948,8 @@ impl Mapping {
match config.commit_mode() {
Commit::Lazy => {}
Commit::Populate | Commit::Lock => {
+ // Memory backed up front stays backed, so the allocator never faults it in again.
+ region.clock.keeps_pages.store(true, Ordering::Relaxed);
// SAFETY: the data range is inside the reservation and holds nothing yet.
unsafe { sys::populate(data, data_len) };
if config.commit_mode() == Commit::Lock {
@@ -1145,6 +1179,75 @@ mod test {
}
}
+ /// Whether every page of the `len` bytes from `ptr` is resident.
+ #[cfg(not(miri))]
+ fn resident(ptr: *mut u8, len: usize) -> bool {
+ // SAFETY: sysconf has no preconditions.
+ let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize;
+ let mut pages = std::vec![0_u8; len.div_ceil(page)];
+ // SAFETY: the range is mapped, and the vector has a byte for each of its pages.
+ let status = unsafe { libc::mincore(ptr.cast(), len, pages.as_mut_ptr().cast()) };
+ status == 0 && pages.iter().all(|&page| page & 1 == 1)
+ }
+
+ /// Writes old contents into a block of whole chunks, frees it, trims the region and asks for a
+ /// zeroed block of the same size, which reuses the same chunks. `before_free` runs on the
+ /// block just before it is freed. Returns the block's address and whether the zeroed one read
+ /// as zeros.
+ fn reuse_after_trim(
+ region: &Region<'_>,
+ before_free: impl FnOnce(NonNull),
+ ) -> (NonNull, bool) {
+ let heap = region.heap().unwrap();
+ let layout = Layout::from_size_align(MIB, 16).unwrap();
+ let block = heap.alloc(layout).unwrap();
+ // SAFETY: the block holds a mebibyte.
+ unsafe { block.as_ptr().write_bytes(0xAA, MIB) };
+ before_free(block);
+ // SAFETY: the block is live with this layout.
+ unsafe { heap.dealloc(block, layout) };
+ heap.flush();
+ region.trim();
+ let zeroed = heap.alloc_zeroed(layout).unwrap();
+ assert_eq!(zeroed, block, "the zeroed block reuses the same chunks");
+ // SAFETY: the block holds a mebibyte.
+ let bytes = unsafe { slice::from_raw_parts(zeroed.as_ptr(), MIB) };
+ (block, bytes.iter().all(|&byte| byte == 0))
+ }
+
+ #[test]
+ #[cfg(not(miri))]
+ fn memory_the_kernel_will_not_take_back_is_cleared_for_zeroed_requests() {
+ let mapping = Mapping::new(&config(16 * MIB)).unwrap();
+ let mut locked = true;
+ // A program that pins its memory, as mlockall does, keeps the kernel from discarding it.
+ let (_, zeroed) = reuse_after_trim(mapping.region(), |block| {
+ // SAFETY: the block is inside the reservation.
+ locked = unsafe { sys::lock(block, MIB) };
+ });
+ // Pinning memory needs a high enough RLIMIT_MEMLOCK, which CI cannot promise.
+ if locked {
+ assert!(zeroed, "a zeroed block kept the old contents of pinned pages");
+ }
+ }
+
+ #[test]
+ #[cfg(not(miri))]
+ fn a_region_backed_up_front_keeps_its_pages() {
+ for commit in [Commit::Populate, Commit::Lock] {
+ let mapping = match Mapping::new(&config(16 * MIB).commit(commit)) {
+ Ok(mapping) => mapping,
+ Err(error) => {
+ assert_eq!((commit, error), (Commit::Lock, Error::LockFailed));
+ continue;
+ }
+ };
+ let (block, zeroed) = reuse_after_trim(mapping.region(), |_| {});
+ assert!(zeroed, "{commit:?}: a zeroed block kept old contents");
+ assert!(resident(block.as_ptr(), MIB), "{commit:?}: the region gave pages back");
+ }
+ }
+
#[test]
fn huge_page_advice_is_harmless() {
let mapping = Mapping::new(&config(16 * MIB).huge_pages(true)).unwrap();
@@ -1173,7 +1276,10 @@ mod loom_test {
purger.join().unwrap();
// Whatever the pass missed has to be announced, or nothing would ever look again.
let mut missed = 0;
- region.chunks.purge_pass(u64::MAX, 0, |run| missed += run.len());
+ region.chunks.purge_pass(u64::MAX, 0, |run| {
+ missed += run.len();
+ true
+ });
assert!(
missed == 0 || region.clock.aging.load(Ordering::Acquire),
"a free chunk is dirty and nothing is going to purge it"
diff --git a/crates/bcmalloc/src/sys.rs b/crates/bcmalloc/src/sys.rs
index 5e3d8cd..dd2ea59 100644
--- a/crates/bcmalloc/src/sys.rs
+++ b/crates/bcmalloc/src/sys.rs
@@ -125,12 +125,14 @@ pub(crate) const DISCARD_ZEROES: bool = cfg!(all(target_os = "linux", not(miri))
/// Tells the kernel the contents of the range are no longer needed, so it may reclaim the physical
/// pages. The range stays mapped and usable. Reading it afterwards returns zeros on Linux and
-/// either the old contents or zeros on macOS.
+/// either the old contents or zeros on macOS. Returns whether the kernel took the advice. It
+/// refuses for pages that are locked in memory, which then keep their contents.
///
/// # Safety
///
/// The range must lie within a live reservation, and no live allocation may overlap it.
-pub(crate) unsafe fn discard(ptr: NonNull, len: usize) {
+#[must_use]
+pub(crate) unsafe fn discard(ptr: NonNull, len: usize) -> bool {
#[cfg(not(miri))]
{
#[cfg(target_os = "linux")]
@@ -140,10 +142,14 @@ pub(crate) unsafe fn discard(ptr: NonNull, len: usize) {
#[cfg(target_os = "macos")]
const ADVICE: libc::c_int = libc::MADV_FREE_REUSABLE;
// SAFETY: forwarded from the caller.
- unsafe { libc::madvise(ptr.as_ptr().cast(), len, ADVICE) };
+ unsafe { libc::madvise(ptr.as_ptr().cast(), len, ADVICE) == 0 }
}
+ // Miri has no pages to give back, and does not take discarded memory for zeros.
#[cfg(miri)]
- let _ = (ptr, len);
+ {
+ let _ = (ptr, len);
+ true
+ }
}
/// Prepares pages that [`discard`] gave back for use again. Linux needs nothing, because the pages
@@ -376,7 +382,7 @@ mod test {
// SAFETY: the range is a live reservation with no other users.
unsafe {
ptr.as_ptr().write(9);
- discard(ptr, LEN);
+ assert!(discard(ptr, LEN));
assert_eq!(ptr.as_ptr().read(), 0);
release(ptr, LEN);
}
@@ -389,7 +395,7 @@ mod test {
// SAFETY: the range is a live reservation with no other users.
unsafe {
ptr.as_ptr().write(9);
- discard(ptr, LEN);
+ assert!(discard(ptr, LEN));
ptr.as_ptr().write(3);
assert_eq!(ptr.as_ptr().read(), 3);
release(ptr, LEN);
diff --git a/crates/bcmalloc/src/testing.rs b/crates/bcmalloc/src/testing.rs
index 59050c6..8e2539a 100644
--- a/crates/bcmalloc/src/testing.rs
+++ b/crates/bcmalloc/src/testing.rs
@@ -634,7 +634,10 @@ impl ChunkModel {
const DELAY: u64 = 5;
self.now += elapsed;
let mut visited = Vec::new();
- let pending = self.bitmap.chunks().purge_pass(self.now, DELAY, |run| visited.extend(run));
+ let pending = self.bitmap.chunks().purge_pass(self.now, DELAY, |run| {
+ visited.extend(run);
+ true
+ });
let len = self.taken.len();
let groups: Vec<_> = (0..len)
.step_by(self.granule)