From e77fb49964b4c69a6785b9aee1702255b0d80f8e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 14:14:27 +0100 Subject: [PATCH] STRA-338 size: model-format: huge pages allocate/settle/coverage and read-ahead pump split (fn_lines 72->30, nesting 5->4) --- crates/model-format/src/huge_pages.rs | 167 ++++++++++++++++---------- crates/model-format/src/readahead.rs | 82 +++++++------ 2 files changed, 147 insertions(+), 102 deletions(-) diff --git a/crates/model-format/src/huge_pages.rs b/crates/model-format/src/huge_pages.rs index 19a3cbc5..f9749c43 100644 --- a/crates/model-format/src/huge_pages.rs +++ b/crates/model-format/src/huge_pages.rs @@ -86,6 +86,29 @@ mod linux { value.checked_add(to - 1).map(|v| v & !(to - 1)) } + fn invalid_input() -> std::io::Error { + std::io::Error::from(std::io::ErrorKind::InvalidInput) + } + + /// A fresh private anonymous read-write mapping of `len` bytes (the kernel picks the address); returns its start. + fn map_anonymous(len: usize) -> std::io::Result { + // SAFETY: a fresh private anonymous mapping; the kernel picks the address; nothing is replaced. + let p = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if p == libc::MAP_FAILED { + return Err(std::io::Error::last_os_error()); + } + Ok(p as usize) + } + /// `HugePages_Free` x `Hugepagesize` of `/proc/meminfo` (0 when absent or unreadable). fn hugetlb_free_bytes() -> usize { let Ok(text) = std::fs::read_to_string("/proc/meminfo") else { return 0 }; @@ -105,52 +128,50 @@ mod linux { impl HugeBuffer { /// A zeroed, faulted-in buffer of `len` bytes (`len > 0`), or the OS error. The caller fills every byte. pub(crate) fn allocate(len: usize) -> std::io::Result { - let invalid = || std::io::Error::from(std::io::ErrorKind::InvalidInput); if len == 0 || mode() == Mode::Off { - return Err(invalid()); + return Err(invalid_input()); } - let page = rustix::param::page_size(); - if mode() == Mode::On { - let map_len = round_up(len, HUGE).ok_or_else(invalid)?; - if hugetlb_free_bytes() >= map_len { - // SAFETY: a fresh private anonymous mapping; the kernel picks the address; nothing is replaced. - let p = unsafe { - libc::mmap( - std::ptr::null_mut(), - map_len, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE - | libc::MAP_ANONYMOUS - | libc::MAP_HUGETLB - | libc::MAP_HUGE_2MB - | libc::MAP_POPULATE, - -1, - 0, - ) - }; - if p != libc::MAP_FAILED { - return Ok(Self::register(p as usize, map_len, len, true)); - } - } + if mode() == Mode::On + && let Some(buffer) = Self::allocate_hugetlb(len)? + { + return Ok(buffer); + } + Self::allocate_thp(len) + } + + /// A `MAP_HUGETLB` mapping when the host has enough free hugetlbfs pages and the kernel grants it, else `None`. + fn allocate_hugetlb(len: usize) -> std::io::Result> { + let map_len = round_up(len, HUGE).ok_or_else(invalid_input)?; + if hugetlb_free_bytes() < map_len { + return Ok(None); } - let map_len = round_up(len, page).ok_or_else(invalid)?; - let reserve = map_len.checked_add(HUGE).ok_or_else(invalid)?; // SAFETY: a fresh private anonymous mapping; the kernel picks the address; nothing is replaced. let p = unsafe { libc::mmap( std::ptr::null_mut(), - reserve, + map_len, libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + libc::MAP_PRIVATE + | libc::MAP_ANONYMOUS + | libc::MAP_HUGETLB + | libc::MAP_HUGE_2MB + | libc::MAP_POPULATE, -1, 0, ) }; if p == libc::MAP_FAILED { - return Err(std::io::Error::last_os_error()); + return Ok(None); } - let start = p as usize; - let base = round_up(start, HUGE).ok_or_else(invalid)?; + Ok(Some(Self::register(p as usize, map_len, len, true))) + } + + /// A 2 MiB-aligned anonymous mapping advised for transparent huge pages and faulted in. + fn allocate_thp(len: usize) -> std::io::Result { + let map_len = round_up(len, rustix::param::page_size()).ok_or_else(invalid_input)?; + let reserve = map_len.checked_add(HUGE).ok_or_else(invalid_input)?; + let start = map_anonymous(reserve)?; + let base = round_up(start, HUGE).ok_or_else(invalid_input)?; let (head, tail) = (base - start, reserve - (base - start) - map_len); // SAFETY: both trims lie inside the mapping just made and outside [base, base + map_len); page-aligned. unsafe { @@ -162,6 +183,12 @@ mod linux { } } let buffer = Self::register(base, map_len, len, false); + buffer.advise_and_populate()?; + Ok(buffer) + } + + fn advise_and_populate(&self) -> std::io::Result<()> { + let (base, map_len) = (self.base, self.map_len); // SAFETY: advice over our own live mapping; MADV_HUGEPAGE changes no contents (EINVAL without THP support: ignored). unsafe { libc::madvise(base as *mut libc::c_void, map_len, libc::MADV_HUGEPAGE); @@ -171,10 +198,10 @@ mod linux { if unsafe { libc::madvise(base as *mut libc::c_void, map_len, libc::MADV_POPULATE_WRITE) } != 0 { let error = std::io::Error::last_os_error(); if error.raw_os_error() != Some(libc::EINVAL) { - return Err(error); // ENOMEM and friends: `buffer` drops and unmaps + return Err(error); // ENOMEM and friends: the buffer drops and unmaps } } - Ok(buffer) + Ok(()) } fn register(base: usize, map_len: usize, len: usize, hugetlb: bool) -> Self { LIVE.lock().unwrap_or_else(|p| p.into_inner()).push((base, map_len, hugetlb)); @@ -231,15 +258,19 @@ mod linux { mapped_bytes: live.iter().map(|e| e.1 as u64).sum(), ..Coverage::default() }; + add_smaps_totals(&smaps, &live, &mut out); + Some(out) + } + + /// Adds the huge-page fields of the smaps entries that overlap a live buffer. + fn add_smaps_totals(smaps: &str, live: &[(usize, usize, bool)], out: &mut Coverage) { let mut inside = false; for line in smaps.lines() { let mut words = line.split_whitespace(); let Some(first) = words.next() else { continue }; - if let Some((a, b)) = first.split_once('-').filter(|_| !first.ends_with(':')) { - if let (Ok(a), Ok(b)) = (usize::from_str_radix(a, 16), usize::from_str_radix(b, 16)) { - inside = live.iter().any(|&(base, len, _)| a < base + len && base < b); - continue; - } + if let Some((a, b)) = smaps_range(first) { + inside = live.iter().any(|&(base, len, _)| a < base + len && base < b); + continue; } if inside { let mut kib = || words.next().and_then(|v| v.parse::().ok()).unwrap_or(0) * 1024; @@ -250,7 +281,12 @@ mod linux { } } } - Some(out) + } + + /// The address range of a smaps entry header (`start-end perms ...`); `None` for any other line. + fn smaps_range(first: &str) -> Option<(usize, usize)> { + let (a, b) = first.split_once('-').filter(|_| !first.ends_with(':'))?; + Some((usize::from_str_radix(a, 16).ok()?, usize::from_str_radix(b, 16).ok()?)) } fn gib(bytes: u64) -> f64 { @@ -277,34 +313,10 @@ mod linux { } let before = coverage()?; let mut text = line("after fill", &before); - let aligned: u64 = LIVE - .lock() - .unwrap_or_else(|p| p.into_inner()) - .iter() - .filter(|e| !e.2) - .map(|e| (e.1 & !(HUGE - 1)) as u64) - .sum(); + let aligned: u64 = thp_ranges().iter().map(|r| r.1 as u64).sum(); if before.thp_bytes < aligned { let t = std::time::Instant::now(); - let ranges: Vec<(usize, usize)> = LIVE - .lock() - .unwrap_or_else(|p| p.into_inner()) - .iter() - .filter(|e| !e.2) - .map(|e| (e.0, e.1 & !(HUGE - 1))) - .collect(); - // linux/mman-common.h MADV_COLLAPSE = 25 (6.1+). Spelled out because libc 0.2.190 does not define it for the musl targets - // (the static CLI build failed to compile); glibc's libc::MADV_COLLAPSE has the same value. - const MADV_COLLAPSE: libc::c_int = 25; - let mut failed = 0usize; - let mut last_error = 0i32; - for (base, len) in ranges.into_iter().filter(|r| r.1 > 0) { - // SAFETY: advice over a live mapping of ours; MADV_COLLAPSE copies pages into a huge page without changing contents. - if unsafe { libc::madvise(base as *mut libc::c_void, len, MADV_COLLAPSE) } != 0 { - failed += 1; - last_error = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - } - } + let (failed, last_error) = collapse(&thp_ranges()); let after = coverage().unwrap_or(before); text.push_str(&format!( "\n{}; MADV_COLLAPSE {:.2} s, {failed} buffers incomplete (last errno {last_error})", @@ -315,6 +327,29 @@ mod linux { Some(text) } + /// The (base, whole-2-MiB-pages length) of every live transparent-huge-page buffer. + fn thp_ranges() -> Vec<(usize, usize)> { + let live = LIVE.lock().unwrap_or_else(|p| p.into_inner()); + live.iter().filter(|e| !e.2).map(|e| (e.0, e.1 & !(HUGE - 1))).collect() + } + + /// Asks the kernel to collapse each range into huge pages; returns (ranges that failed, last errno). + fn collapse(ranges: &[(usize, usize)]) -> (usize, i32) { + // linux/mman-common.h MADV_COLLAPSE = 25 (6.1+). Spelled out because libc 0.2.190 does not define it for the musl targets + // (the static CLI build failed to compile); glibc's libc::MADV_COLLAPSE has the same value. + const MADV_COLLAPSE: libc::c_int = 25; + let mut failed = 0usize; + let mut last_error = 0i32; + for &(base, len) in ranges.iter().filter(|r| r.1 > 0) { + // SAFETY: advice over a live mapping of ours; MADV_COLLAPSE copies pages into a huge page without changing contents. + if unsafe { libc::madvise(base as *mut libc::c_void, len, MADV_COLLAPSE) } != 0 { + failed += 1; + last_error = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + } + } + (failed, last_error) + } + #[cfg(test)] mod tests { use super::*; diff --git a/crates/model-format/src/readahead.rs b/crates/model-format/src/readahead.rs index 5716480f..b58313dd 100644 --- a/crates/model-format/src/readahead.rs +++ b/crates/model-format/src/readahead.rs @@ -136,46 +136,56 @@ pub(crate) fn with_read_ahead( } advise_sequential(file); thread::scope(|scope| { - scope.spawn(move || { - let mut offset = 0u64; - let mut advised = start; - while offset < bytes { - let count = (bytes - offset).min(CHUNK_BYTES as u64) as usize; - #[cfg(target_os = "linux")] - { - let target = (start + offset + count as u64 + WILLNEED_AHEAD).min(start + bytes); - if target > advised { - advise_willneed(file, advised, target - advised); - advised = target; - } - } - #[cfg(not(target_os = "linux"))] - let _ = (&mut advised, advise_willneed as fn(&File, u64, u64)); - let mut buffer = pool.lock().ok().and_then(|mut p| p.pop()).unwrap_or_default(); - buffer.resize(count, 0); - if let Err(error) = read_exact_at(file, &mut buffer, start + offset) { - for tx in &senders { - let _ = tx.send(Err(io::Error::new(error.kind(), error.to_string()))); - } - return; - } - // The bytes are in `buffer` now; the cached pages behind them are not needed again by this pass. - evict_span(file, start + offset, count as u64); - let chunk = Arc::new(Chunk { offset, data: buffer, pool: Arc::clone(&pool) }); - let mut any = false; - for tx in &senders { - any |= tx.send(Ok(Arc::clone(&chunk))).is_ok(); - } - if !any { - return; - } - offset += count as u64; - } - }); + scope.spawn(move || pump(file, (start, bytes), &senders, &pool)); body(receivers) }) } +/// The reader thread: reads the span chunk by chunk and sends every chunk to every consumer, until the span is +/// read, a read fails (the error goes to all consumers) or no consumer is left. +fn pump(file: &File, (start, bytes): (u64, u64), senders: &[SyncSender>>], pool: &Pool) { + let mut offset = 0u64; + let mut advised = start; + while offset < bytes { + let count = (bytes - offset).min(CHUNK_BYTES as u64) as usize; + advise_ahead(file, &mut advised, (start, bytes), offset + count as u64); + let mut buffer = pool.lock().ok().and_then(|mut p| p.pop()).unwrap_or_default(); + buffer.resize(count, 0); + if let Err(error) = read_exact_at(file, &mut buffer, start + offset) { + for tx in senders { + let _ = tx.send(Err(io::Error::new(error.kind(), error.to_string()))); + } + return; + } + // The bytes are in `buffer` now; the cached pages behind them are not needed again by this pass. + evict_span(file, start + offset, count as u64); + let chunk = Arc::new(Chunk { offset, data: buffer, pool: Arc::clone(pool) }); + let mut any = false; + for tx in senders { + any |= tx.send(Ok(Arc::clone(&chunk))).is_ok(); + } + if !any { + return; + } + offset += count as u64; + } +} + +/// Asks the kernel to fetch up to `WILLNEED_AHEAD` bytes beyond `read_end` (an offset in the span), each byte once. +#[cfg(target_os = "linux")] +fn advise_ahead(file: &File, advised: &mut u64, (start, bytes): (u64, u64), read_end: u64) { + let target = (start + read_end + WILLNEED_AHEAD).min(start + bytes); + if target > *advised { + advise_willneed(file, *advised, target - *advised); + *advised = target; + } +} + +#[cfg(not(target_os = "linux"))] +fn advise_ahead(_file: &File, advised: &mut u64, _span: (u64, u64), _read_end: u64) { + let _ = (advised, advise_willneed as fn(&File, u64, u64)); +} + #[cfg(test)] mod tests { use super::*;