diff --git a/docs/TODO.txt b/docs/TODO.txt index e975fce8c..07125373a 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -1,3 +1,10 @@ +[ ] Run end-to-end `flare run --prefix-cache-memory --prefix-cache-disk ` + A/B startup timing checks against `main` under Linux THP `enabled=madvise, + defrag=madvise` on fragmented and unfragmented memory, plus live RDMA + `ibv_reg_mr` registration and 16 KiB/64 KiB ARM64 Linux kernel validation + for `eos::map_host` (#616). Also audit `selene-manager/src/arena.rs` for + unconditional `MADV_HUGEPAGE` under synchronous THP defragmentation. + [ ] Fix native TP4 shutdown reporting "free(): double free detected in tcache 2" after server drain with Inkling 2 cores. Reproduces with compiled and uncompiled graphs; preserve the successful request drain and GPU release. diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index f4294f83a..5d48ff9fe 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -516,9 +516,24 @@ offload event. Transfers move records in windows of at most 64 pages plus the multi-slot row. The pool contains warm checkpoint slots plus automatic intake slots. It is one -4 KiB aligned anonymous mapping (`MAP_PRIVATE`, `MAP_ANONYMOUS`, advised for -transparent huge pages with `MADV_HUGEPAGE` before prefaulting via -`MADV_POPULATE_WRITE`), registered once at startup. Rows use each +page-aligned anonymous mapping (`MAP_PRIVATE`, `MAP_ANONYMOUS`), prefaulted +writable (in bounded chunks on Unix) and registered once at startup. On Linux, +`eos::map_host` inspects +`/sys/kernel/mm/transparent_hugepage/{enabled,defrag,hpage_pmd_size}` to choose +how to request transparent huge pages without triggering sustained synchronous +memory compaction: non-blocking defragmentation policies (`defer` or `never`) +advise `MADV_HUGEPAGE` across the single mapping upfront, while `enabled=always` +with `defrag=madvise` or `defer+madvise` uses the kernel's opportunistic +hugepage path without `MADV_HUGEPAGE`. Under policies where `MADV_HUGEPAGE` can +trigger synchronous direct compaction, `eos::map_host` anchors one shared +`anon_vma` on the unsplit mapping, walks PMD-aligned chunks up to +`max(16 MiB, hpage_pmd_size)` while checking `/proc/buddyinfo` free hugepage +supply across NUMA nodes allowed by `/proc/self/status` (`Mems_allowed_list`), +chunk fault latency, and consecutive `/proc/vmstat` `compact_stall` increments, +falls back to base pages for the remainder of the slab when huge pages are scarce +or compaction stalls begin, and applies a whole-range `madvise` (`MADV_NOHUGEPAGE` +after fallback, `MADV_HUGEPAGE` otherwise) once all pages are populated so Linux +merges the mapping back into one contiguous VMA before CUDA registration. Rows use each rank's page share across as many slots as needed; their pieces need not be contiguous. CPU readers traverse pieces in rank order, preserving disk bytes and streaming xxh3 checksum values. After copy-out, Selene compares local ranks' @@ -972,9 +987,13 @@ Offload limits interference through bounded work and explicit ownership: rejects unknown keys, including `disk_transport`. - `LoadOptions` carries `prefix_cache: PrefixCacheOffload` with the memory size, directory, disk limit, shutdown drain, max age, and pool. -- The `Prepare host prefix cache` startup phase reports the slot pool's size - and slot count, CPU input limits, the record directory, the disk limit, the - scanned record count, and the `staged` transport. +- The `Prepare host prefix cache` startup phase updates its live step detail as + it allocates a split host slab or populates and CUDA-registers a contiguous + host slab and scans existing disk records. On completion, it reports the slot + pool's size, slot count, and separate elapsed durations (`allocate` for split + pools, or `populate` and `register` for contiguous registered pools), CPU + input limits, and the record directory, disk limit, scanned record count, + `staged` transport, and `scan` duration. - Metrics expose `flare_host_cache_slots_in_use`, `flare_host_cache_slots_total` (including intake), and `flare_host_cache_intake_slots`. Used slots include pages, every row piece, and staging allocations from the same local pool. diff --git a/eos/src/unix.rs b/eos/src/unix.rs index 178b0bfc1..f0932fd20 100644 --- a/eos/src/unix.rs +++ b/eos/src/unix.rs @@ -9,6 +9,7 @@ use std::{ io, os::{fd::AsRawFd, unix::fs::OpenOptionsExt}, path::Path, + time::Duration, }; /// # Safety @@ -82,40 +83,686 @@ pub fn lower_priority(nice: i32) { } } -pub fn map_host(bytes: usize) -> io::Result { - let ptr = unsafe { - libc::mmap( - std::ptr::null_mut(), - bytes, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - if ptr == libc::MAP_FAILED { - return Err(io::Error::last_os_error()); +/// Maximum bytes prefaulted per `MADV_POPULATE_WRITE` call to bound `mmap_lock` hold time. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +const POPULATE_CHUNK_BYTES: usize = 64 << 20; + +/// Upper bound on adaptive hugepage chunk size (unless the kernel PMD size is larger). +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +const ADAPTIVE_MAX_CHUNK_BYTES: usize = 16 << 20; + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ThpEnabled { + Always, + Madvise, + Never, + Unknown, +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ThpDefrag { + Always, + Defer, + DeferPlusMadvise, + Madvise, + Never, + Unknown, +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PopulationMode { + BasePages, + EagerHugepage, + KernelDefaultOpportunistic, + AdaptiveHugepage { fallback_needs_nohugepage: bool }, +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct ThpPolicy { + page_size: usize, + hpage_pmd_size: Option, + mode: PopulationMode, +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ChunkStallCheck { + Healthy, + CheckCompactStall, + Stalled, +} + +struct MappingGuard { + ptr: *mut libc::c_void, + bytes: usize, +} + +impl MappingGuard { + fn map(bytes: usize) -> io::Result { + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + bytes, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if ptr == libc::MAP_FAILED { + return Err(io::Error::last_os_error()); + } + Ok(Self { ptr, bytes }) + } + + fn ptr(&self) -> *mut libc::c_void { + self.ptr + } + + fn commit(self) -> usize { + let address = self.ptr as usize; + std::mem::forget(self); + address + } +} + +impl Drop for MappingGuard { + fn drop(&mut self) { + // SAFETY: `self.ptr` and `self.bytes` come directly from `MappingGuard::map` + // and ownership has not been transferred through `commit`. + unsafe { + libc::munmap(self.ptr, self.bytes); + } + } +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn parse_active_sysfs_token(contents: &str) -> Option<&str> { + contents + .split_whitespace() + .find_map(|token| token.strip_prefix('[')?.strip_suffix(']')) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn parse_thp_enabled(contents: &str) -> ThpEnabled { + match parse_active_sysfs_token(contents) { + Some("always") => ThpEnabled::Always, + Some("madvise") => ThpEnabled::Madvise, + Some("never") => ThpEnabled::Never, + _ => ThpEnabled::Unknown, + } +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn parse_thp_defrag(contents: &str) -> ThpDefrag { + match parse_active_sysfs_token(contents) { + Some("always") => ThpDefrag::Always, + Some("defer") => ThpDefrag::Defer, + Some("defer+madvise") => ThpDefrag::DeferPlusMadvise, + Some("madvise") => ThpDefrag::Madvise, + Some("never") => ThpDefrag::Never, + _ => ThpDefrag::Unknown, + } +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn validate_hpage_pmd_size(hpage_pmd_size: usize, base_page_size: usize) -> Option { + if base_page_size.is_power_of_two() + && hpage_pmd_size.is_power_of_two() + && hpage_pmd_size > base_page_size + { + Some(hpage_pmd_size) + } else { + None + } +} + +/// Derive the default Linux PMD hugepage size from the base page size when +/// `/sys/kernel/mm/transparent_hugepage/hpage_pmd_size` is unreadable: +/// 2 MiB on 4 KiB kernels, 32 MiB on 16 KiB kernels, and 512 MiB on 64 KiB kernels. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn default_hpage_pmd_size(base_page_size: usize) -> Option { + if !base_page_size.is_power_of_two() || base_page_size < 8 { + return None; + } + let derived = (base_page_size / 8).checked_mul(base_page_size)?; + validate_hpage_pmd_size(derived, base_page_size) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn parse_hpage_pmd_size(contents: &str, base_page_size: usize) -> Option { + let parsed = contents.trim().parse::().ok()?; + validate_hpage_pmd_size(parsed, base_page_size) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn select_population_mode( + enabled: ThpEnabled, + defrag: ThpDefrag, + hpage_pmd_size: Option, +) -> PopulationMode { + if hpage_pmd_size.is_none() || enabled == ThpEnabled::Never { + return PopulationMode::BasePages; + } + if matches!(defrag, ThpDefrag::Defer | ThpDefrag::Never) { + return PopulationMode::EagerHugepage; + } + if enabled == ThpEnabled::Always + && matches!(defrag, ThpDefrag::Madvise | ThpDefrag::DeferPlusMadvise) + { + return PopulationMode::KernelDefaultOpportunistic; + } + let fallback_needs_nohugepage = matches!(enabled, ThpEnabled::Always | ThpEnabled::Unknown) + || matches!(defrag, ThpDefrag::Always | ThpDefrag::Unknown); + PopulationMode::AdaptiveHugepage { + fallback_needs_nohugepage, + } +} + +/// Parse `Mems_allowed_list:` from `/proc/self/status` into inclusive NUMA node +/// ranges. Returns `None` when the field is absent or malformed so callers fall +/// back to summing all nodes in `/proc/buddyinfo`. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn parse_mems_allowed_list(status: &str) -> Option> { + let raw = status.lines().find_map(|line| { + line.strip_prefix("Mems_allowed_list:") + .map(str::trim) + .filter(|s| !s.is_empty()) + })?; + let mut ranges = Vec::new(); + for part in raw.split(',') { + let part = part.trim(); + if part.is_empty() { + return None; + } + if let Some((start, end)) = part.split_once('-') { + let start = start.trim().parse::().ok()?; + let end = end.trim().parse::().ok()?; + if start > end { + return None; + } + ranges.push((start, end)); + } else { + let node = part.parse::().ok()?; + ranges.push((node, node)); + } + } + (!ranges.is_empty()).then_some(ranges) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn node_allowed(node: u32, allowed: Option<&[(u32, u32)]>) -> bool { + match allowed { + None => true, + Some(ranges) => ranges.iter().any(|&(start, end)| node >= start && node <= end), + } +} + +/// Parse weighted free PMD-sized huge pages from `/proc/buddyinfo`, optionally +/// restricted to NUMA nodes allowed by `/proc/self/status` (`Mems_allowed_list`). +/// +/// Counts `Normal` and `Movable` zones when present, falling back to all parseable +/// zones on platforms without those zone names. Returns `None` when the inputs are +/// invalid or no parseable zone lines exist. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn parse_buddyinfo_free_hugepages_for_nodes( + contents: &str, + hpage_pmd_size: usize, + base_page_size: usize, + allowed_nodes: Option<&[(u32, u32)]>, +) -> Option { + validate_hpage_pmd_size(hpage_pmd_size, base_page_size)?; + let huge_order = (hpage_pmd_size / base_page_size).trailing_zeros() as usize; + + let mut preferred_total = 0u64; + let mut saw_preferred = false; + let mut all_total = 0u64; + let mut saw_any = false; + + for line in contents.lines() { + let mut tokens = line.split_whitespace(); + let mut node_id = None; + let mut saw_zone = false; + while let Some(token) = tokens.next() { + if token == "Node" + && let Some(raw_node) = tokens.next() + { + node_id = raw_node.trim_end_matches(',').parse::().ok(); + } else if token == "zone" { + saw_zone = true; + break; + } + } + if !saw_zone { + continue; + } + if let Some(node) = node_id + && !node_allowed(node, allowed_nodes) + { + continue; + } + let Some(zone_name) = tokens.next() else { + continue; + }; + let mut zone_total = 0u64; + let mut parsed_any_order = false; + let mut valid_line = true; + for (order, token) in tokens.enumerate() { + let Ok(count) = token.parse::() else { + valid_line = false; + break; + }; + parsed_any_order = true; + if order >= huge_order && count > 0 { + let weight = u32::try_from(order - huge_order) + .ok() + .and_then(|shift| 1u64.checked_shl(shift)) + .unwrap_or(u64::MAX); + zone_total = zone_total.saturating_add(count.saturating_mul(weight)); + } + } + if !valid_line || !parsed_any_order { + continue; + } + saw_any = true; + all_total = all_total.saturating_add(zone_total); + if matches!(zone_name, "Normal" | "Movable") { + saw_preferred = true; + preferred_total = preferred_total.saturating_add(zone_total); + } + } + + if saw_preferred { + Some(preferred_total) + } else if saw_any { + Some(all_total) + } else { + None + } +} + +#[cfg(test)] +fn parse_buddyinfo_free_hugepages( + contents: &str, + hpage_pmd_size: usize, + base_page_size: usize, +) -> Option { + parse_buddyinfo_free_hugepages_for_nodes(contents, hpage_pmd_size, base_page_size, None) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn parse_vmstat_counter(contents: &str, name: &str) -> Option { + contents.lines().find_map(|line| { + let mut fields = line.split_whitespace(); + if fields.next()? != name { + return None; + } + let value = fields.next()?.parse::().ok()?; + fields.next().is_none().then_some(value) + }) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn buddyinfo_required_hugepages(chunk_hugepages: u64, total_hugepages: u64) -> u64 { + chunk_hugepages.saturating_add((total_hugepages / 16).min(32)) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn stall_thresholds(chunk_bytes: usize) -> (Duration, Duration) { + const GIB_PER_SEC: u128 = 1u128 << 30; + const QUARTER_GIB_PER_SEC: u128 = 256u128 << 20; + const NS_PER_SEC: u128 = 1_000_000_000; + let bytes = chunk_bytes as u128; + let floor_ns = bytes.saturating_mul(NS_PER_SEC) / GIB_PER_SEC; + let ceiling_ns = bytes.saturating_mul(NS_PER_SEC) / QUARTER_GIB_PER_SEC; + let stall_floor = + Duration::from_millis(15).max(Duration::from_nanos(u64::try_from(floor_ns).unwrap_or(u64::MAX))); + let hard_ceiling = Duration::from_millis(50) + .max(Duration::from_nanos(u64::try_from(ceiling_ns).unwrap_or(u64::MAX))); + (stall_floor, hard_ceiling) +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn classify_chunk_elapsed(elapsed: Duration, chunk_bytes: usize) -> ChunkStallCheck { + let (stall_floor, hard_ceiling) = stall_thresholds(chunk_bytes); + if elapsed <= stall_floor { + ChunkStallCheck::Healthy + } else if elapsed > hard_ceiling { + ChunkStallCheck::Stalled + } else { + ChunkStallCheck::CheckCompactStall + } +} + +#[cfg(target_os = "linux")] +fn read_hpage_pmd_size(base_page_size: usize) -> Option { + match std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size") { + Ok(contents) => parse_hpage_pmd_size(&contents, base_page_size), + Err(_) => default_hpage_pmd_size(base_page_size), + } +} + +#[cfg(target_os = "linux")] +fn detect_thp_policy() -> ThpPolicy { + let base_page_size = page_size(); + let enabled = std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/enabled") + .map(|contents| parse_thp_enabled(&contents)) + .unwrap_or(ThpEnabled::Unknown); + let defrag = std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/defrag") + .map(|contents| parse_thp_defrag(&contents)) + .unwrap_or(ThpDefrag::Unknown); + let hpage_pmd_size = read_hpage_pmd_size(base_page_size); + let mode = select_population_mode(enabled, defrag, hpage_pmd_size); + ThpPolicy { + page_size: base_page_size, + hpage_pmd_size, + mode, + } +} + +#[cfg(target_os = "linux")] +fn read_mems_allowed_list() -> Option> { + let contents = std::fs::read_to_string("/proc/self/status").ok()?; + parse_mems_allowed_list(&contents) +} + +#[cfg(target_os = "linux")] +fn read_buddyinfo_free_hugepages( + hpage_pmd_size: usize, + base_page_size: usize, + allowed_nodes: Option<&[(u32, u32)]>, +) -> Option { + let contents = std::fs::read_to_string("/proc/buddyinfo").ok()?; + parse_buddyinfo_free_hugepages_for_nodes(&contents, hpage_pmd_size, base_page_size, allowed_nodes) +} + +#[cfg(target_os = "linux")] +fn read_compact_stall() -> Option { + let contents = std::fs::read_to_string("/proc/vmstat").ok()?; + parse_vmstat_counter(&contents, "compact_stall") +} + +#[cfg(target_os = "linux")] +fn advise_range(ptr: *mut u8, len: usize, advice: libc::c_int) { + if len == 0 { + return; } - // Advise transparent huge pages before faulting so Linux backs the mapping - // with 2 MiB pages when THP is set to `madvise` rather than faulting 4 KiB - // pages first via MAP_POPULATE. + // SAFETY: `ptr` is page-aligned and `[ptr, ptr + len)` lies inside the caller's mapping. + // Advisory THP hints may return `EINVAL` on kernels without `CONFIG_TRANSPARENT_HUGEPAGE`. unsafe { - libc::madvise(ptr, bytes, libc::MADV_HUGEPAGE); + let _ = libc::madvise(ptr.cast::(), len, advice); + } +} + +fn populate_chunk_volatile(ptr: *mut u8, len: usize, page_size: usize) { + let step = page_size.max(1); + for offset in (0..len).step_by(step) { + // SAFETY: `offset < len` and `[ptr, ptr + len)` is writable. + unsafe { + ptr.add(offset).write_volatile(0); + } + } +} + +fn populate_chunk(ptr: *mut u8, len: usize, page_size: usize) -> io::Result<()> { + if len == 0 { + return Ok(()); } #[cfg(target_os = "linux")] - let populated = unsafe { libc::madvise(ptr, bytes, libc::MADV_POPULATE_WRITE) == 0 }; + loop { + // SAFETY: `ptr` is page-aligned and `[ptr, ptr + len)` lies inside the writable mapping. + let rc = unsafe { libc::madvise(ptr.cast::(), len, libc::MADV_POPULATE_WRITE) }; + if rc == 0 { + return Ok(()); + } + let error = io::Error::last_os_error(); + match error.raw_os_error() { + Some(libc::EINTR) => continue, + Some(libc::EINVAL) | Some(libc::ENOSYS) => { + populate_chunk_volatile(ptr, len, page_size); + return Ok(()); + } + _ => return Err(error), + } + } #[cfg(not(target_os = "linux"))] - let populated = false; - if !populated { - let step = page_size().max(1); - for offset in (0..bytes).step_by(step) { - // SAFETY: `offset < bytes` and the mapping is writable. - unsafe { - ptr.cast::().add(offset).write_volatile(0); + { + populate_chunk_volatile(ptr, len, page_size); + Ok(()) + } +} + +fn populate_chunks( + ptr: *mut u8, + len: usize, + chunk_bytes: usize, + page_size: usize, +) -> io::Result<()> { + let chunk_bytes = chunk_bytes.max(page_size.max(1)); + let mut offset = 0usize; + while offset < len { + let step = (len - offset).min(chunk_bytes); + // SAFETY: `offset + step <= len` and `offset` stays page-aligned when `ptr` and + // `chunk_bytes` are page-aligned. + populate_chunk(unsafe { ptr.add(offset) }, step, page_size)?; + offset += step; + } + Ok(()) +} + +/// Populate a Linux anonymous mapping under synchronous-compaction THP policies while +/// preserving a single merged VMA upon return. +/// +/// Before issuing any sub-range `MADV_HUGEPAGE` that splits the VMA, this function +/// faults one base page on the unsplit mapping so Linux attaches a single shared +/// `anon_vma`. Every split child inherits that `anon_vma`, allowing the final +/// whole-range `madvise` to collapse all sub-VMAs back into one VMA before CUDA or +/// RDMA host registration. +#[cfg(target_os = "linux")] +fn populate_adaptive_with( + base_ptr: *mut u8, + bytes: usize, + hpage_size: usize, + page_size: usize, + fallback_needs_nohugepage: bool, + mut read_free_hugepages: impl FnMut() -> Option, + mut read_compact_stall: impl FnMut() -> Option, +) -> io::Result<()> { + let base = base_ptr as usize; + let Some(end) = base.checked_add(bytes) else { + return Err(io::Error::from_raw_os_error(libc::EINVAL)); + }; + let mut aligned_end = (end / hpage_size) * hpage_size; + let Some(aligned_start) = base + .checked_next_multiple_of(hpage_size) + .filter(|&start| start < aligned_end) + else { + if fallback_needs_nohugepage { + advise_range(base_ptr, bytes, libc::MADV_NOHUGEPAGE); + } + return populate_chunks(base_ptr, bytes, POPULATE_CHUNK_BYTES, page_size); + }; + + // Single exact PMD mapping: no sub-range split is needed. + if aligned_start == base && aligned_end == end && bytes == hpage_size { + let required = buddyinfo_required_hugepages(1, 1); + let low_hugepages = read_free_hugepages().is_some_and(|free| free < required); + if low_hugepages { + if fallback_needs_nohugepage { + advise_range(base_ptr, bytes, libc::MADV_NOHUGEPAGE); + } + } else { + advise_range(base_ptr, bytes, libc::MADV_HUGEPAGE); + } + return populate_chunks(base_ptr, bytes, POPULATE_CHUNK_BYTES, page_size); + } + + if fallback_needs_nohugepage { + advise_range(base_ptr, bytes, libc::MADV_NOHUGEPAGE); + } + + // Anchor one shared `anon_vma` on the unsplit mapping before any sub-range `madvise`. + if aligned_start > base { + // SAFETY: `bytes > 0` and the mapping is writable. + unsafe { + base_ptr.write_volatile(0); + } + } else if aligned_end < end { + // SAFETY: `bytes > 0` and `bytes - 1` lies within the writable mapping. + unsafe { + base_ptr.add(bytes - 1).write_volatile(0); + } + } else { + // Both ends are PMD-aligned and `bytes >= 2 * hpage_size`. Anchor the final + // byte and keep the hugepage interior disjoint from that trailing base page. + // SAFETY: `bytes > 0` and `bytes - 1` lies within the writable mapping. + unsafe { + base_ptr.add(bytes - 1).write_volatile(0); + } + aligned_end -= hpage_size; + } + + let prefix_len = aligned_start - base; + if prefix_len > 0 { + populate_chunks(base_ptr, prefix_len, POPULATE_CHUNK_BYTES, page_size)?; + } + + let total_hugepages = ((aligned_end - aligned_start) / hpage_size) as u64; + let max_chunk = ADAPTIVE_MAX_CHUNK_BYTES.max(hpage_size); + let mut offset = prefix_len; + let interior_end = aligned_end - base; + let mut chunk_bytes = hpage_size; + let mut fell_back = false; + let mut consecutive_compact_stalls = 0u32; + + while offset < interior_end { + let len = (interior_end - offset).min(chunk_bytes); + let chunk_hugepages = (len / hpage_size) as u64; + let required = buddyinfo_required_hugepages(chunk_hugepages, total_hugepages); + if read_free_hugepages().is_some_and(|free| free < required) { + fell_back = true; + break; + } + let stall_before = read_compact_stall(); + // SAFETY: `offset + len <= bytes` and `offset` is PMD-aligned (hence page-aligned). + let chunk_ptr = unsafe { base_ptr.add(offset) }; + advise_range(chunk_ptr, len, libc::MADV_HUGEPAGE); + let started = std::time::Instant::now(); + populate_chunk(chunk_ptr, len, page_size)?; + let elapsed = started.elapsed(); + offset += len; + + match classify_chunk_elapsed(elapsed, len) { + ChunkStallCheck::Healthy => { + consecutive_compact_stalls = 0; + } + ChunkStallCheck::Stalled => { + fell_back = true; + break; + } + ChunkStallCheck::CheckCompactStall => { + if let (Some(before), Some(after)) = (stall_before, read_compact_stall()) + && after > before + { + consecutive_compact_stalls += 1; + if consecutive_compact_stalls >= 2 { + fell_back = true; + break; + } + } else { + consecutive_compact_stalls = 0; + } } } + chunk_bytes = chunk_bytes.saturating_mul(2).min(max_chunk); + } + + if offset < bytes { + // SAFETY: `offset < bytes` and `offset` is PMD-aligned (hence page-aligned). + // When `fallback_needs_nohugepage` is true, the unsplit mapping already carries + // `MADV_NOHUGEPAGE` and `[offset, bytes)` was never advised `MADV_HUGEPAGE`. + let tail_ptr = unsafe { base_ptr.add(offset) }; + let tail_len = bytes - offset; + populate_chunks(tail_ptr, tail_len, POPULATE_CHUNK_BYTES, page_size)?; + } + + // All pages are populated writable; unify VMA flags across the whole mapping so Linux + // merges all sub-VMAs back into one contiguous VMA. + let final_advice = if fell_back { + libc::MADV_NOHUGEPAGE + } else { + libc::MADV_HUGEPAGE + }; + advise_range(base_ptr, bytes, final_advice); + Ok(()) +} + +#[cfg(target_os = "linux")] +fn populate_linux(guard: &MappingGuard, policy: &ThpPolicy) -> io::Result<()> { + let base_ptr = guard.ptr().cast::(); + let bytes = guard.bytes; + let page_size = policy.page_size.max(1); + match policy.mode { + PopulationMode::BasePages | PopulationMode::KernelDefaultOpportunistic => { + populate_chunks(base_ptr, bytes, POPULATE_CHUNK_BYTES, page_size) + } + PopulationMode::EagerHugepage => { + advise_range(base_ptr, bytes, libc::MADV_HUGEPAGE); + populate_chunks(base_ptr, bytes, POPULATE_CHUNK_BYTES, page_size) + } + PopulationMode::AdaptiveHugepage { + fallback_needs_nohugepage, + } => { + let hpage_size = policy + .hpage_pmd_size + .expect("adaptive mode requires validated hpage_pmd_size"); + let allowed_nodes = read_mems_allowed_list(); + populate_adaptive_with( + base_ptr, + bytes, + hpage_size, + page_size, + fallback_needs_nohugepage, + || read_buddyinfo_free_hugepages(hpage_size, page_size, allowed_nodes.as_deref()), + read_compact_stall, + ) + } + } +} + +fn map_host_with( + bytes: usize, + populate: impl FnOnce(&MappingGuard) -> io::Result<()>, +) -> io::Result { + if bytes == 0 { + return Err(io::Error::from_raw_os_error(libc::EINVAL)); } - Ok(ptr as usize) + let guard = MappingGuard::map(bytes)?; + populate(&guard)?; + Ok(guard.commit()) +} + +pub fn map_host(bytes: usize) -> io::Result { + map_host_with(bytes, |guard| { + #[cfg(target_os = "linux")] + { + let policy = detect_thp_policy(); + populate_linux(guard, &policy) + } + #[cfg(not(target_os = "linux"))] + { + populate_chunks( + guard.ptr().cast::(), + guard.bytes, + POPULATE_CHUNK_BYTES, + page_size().max(1), + ) + } + }) } /// # Safety @@ -204,6 +851,333 @@ mod tests { let _ = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &before) }; } + #[derive(Debug, PartialEq, Eq)] + struct SmapsVma { + start: usize, + end: usize, + vm_flags: Option>, + } + + fn parse_smaps_header(line: &str) -> Option<(usize, usize)> { + let range = line.split_whitespace().next()?; + let (start, end) = range.split_once('-')?; + let start = usize::from_str_radix(start, 16).ok()?; + let end = usize::from_str_radix(end, 16).ok()?; + (start < end).then_some((start, end)) + } + + fn parse_smaps_intersecting_vmas(smaps: &str, start: usize, end: usize) -> Vec { + let mut intersecting = Vec::new(); + let mut current: Option = None; + for line in smaps.lines() { + if let Some((vma_start, vma_end)) = parse_smaps_header(line) { + if let Some(vma) = current.take() + && vma.start < end + && vma.end > start + { + intersecting.push(vma); + } + current = Some(SmapsVma { + start: vma_start, + end: vma_end, + vm_flags: None, + }); + } else if let Some(rest) = line.strip_prefix("VmFlags:") + && let Some(vma) = current.as_mut() + { + vma.vm_flags = Some(rest.split_whitespace().map(str::to_owned).collect()); + } + } + if let Some(vma) = current + && vma.start < end + && vma.end > start + { + intersecting.push(vma); + } + intersecting + } + + #[test] + fn map_host_rejects_zero_bytes_with_einval() { + let error = map_host(0).unwrap_err(); + assert_eq!(error.raw_os_error(), Some(libc::EINVAL)); + } + + #[test] + fn mapping_guard_unmaps_on_population_error() { + let mut seen_ptr = 0usize; + let error = map_host_with(page_size().max(4096), |guard| { + seen_ptr = guard.ptr() as usize; + Err(io::Error::from_raw_os_error(libc::ENOMEM)) + }) + .unwrap_err(); + assert_ne!(seen_ptr, 0); + assert_eq!(error.raw_os_error(), Some(libc::ENOMEM)); + } + + #[test] + fn thp_sysfs_parsers_extract_active_tokens_and_pmd_sizes() { + assert_eq!( + parse_thp_enabled("[always] madvise never\n"), + ThpEnabled::Always + ); + assert_eq!( + parse_thp_enabled("always [madvise] never\n"), + ThpEnabled::Madvise + ); + assert_eq!( + parse_thp_enabled("always madvise [never]\n"), + ThpEnabled::Never + ); + assert_eq!(parse_thp_enabled("always madvise never\n"), ThpEnabled::Unknown); + assert_eq!(parse_thp_enabled("[future]\n"), ThpEnabled::Unknown); + + assert_eq!( + parse_thp_defrag("[always] defer defer+madvise madvise never\n"), + ThpDefrag::Always + ); + assert_eq!( + parse_thp_defrag("always [defer] defer+madvise madvise never\n"), + ThpDefrag::Defer + ); + assert_eq!( + parse_thp_defrag("always defer [defer+madvise] madvise never\n"), + ThpDefrag::DeferPlusMadvise + ); + assert_eq!( + parse_thp_defrag("always defer defer+madvise [madvise] never\n"), + ThpDefrag::Madvise + ); + assert_eq!( + parse_thp_defrag("always defer defer+madvise madvise [never]\n"), + ThpDefrag::Never + ); + assert_eq!(parse_thp_defrag("unexpected"), ThpDefrag::Unknown); + + assert_eq!(default_hpage_pmd_size(4096), Some(2 << 20)); + assert_eq!(default_hpage_pmd_size(16384), Some(32 << 20)); + assert_eq!(default_hpage_pmd_size(65536), Some(512 << 20)); + assert_eq!(default_hpage_pmd_size(0), None); + assert_eq!(default_hpage_pmd_size(3000), None); + + assert_eq!(parse_hpage_pmd_size("2097152\n", 4096), Some(2 << 20)); + assert_eq!(parse_hpage_pmd_size("33554432\n", 16384), Some(32 << 20)); + assert_eq!(parse_hpage_pmd_size("536870912\n", 65536), Some(512 << 20)); + assert_eq!(parse_hpage_pmd_size("4096\n", 4096), None); + assert_eq!(parse_hpage_pmd_size("3145728\n", 4096), None); + assert_eq!(parse_hpage_pmd_size("0\n", 4096), None); + assert_eq!(parse_hpage_pmd_size("invalid\n", 4096), None); + assert_eq!(parse_hpage_pmd_size("2097152\n", 3000), None); + } + + #[test] + fn population_mode_decision_table_covers_all_policy_combinations() { + let pmd = Some(2 << 20); + for enabled in [ + ThpEnabled::Always, + ThpEnabled::Madvise, + ThpEnabled::Never, + ThpEnabled::Unknown, + ] { + for defrag in [ + ThpDefrag::Always, + ThpDefrag::Defer, + ThpDefrag::DeferPlusMadvise, + ThpDefrag::Madvise, + ThpDefrag::Never, + ThpDefrag::Unknown, + ] { + assert_eq!( + select_population_mode(enabled, defrag, None), + PopulationMode::BasePages + ); + let expected = match (enabled, defrag) { + (ThpEnabled::Never, _) => PopulationMode::BasePages, + (_, ThpDefrag::Defer | ThpDefrag::Never) => PopulationMode::EagerHugepage, + (ThpEnabled::Always, ThpDefrag::Madvise | ThpDefrag::DeferPlusMadvise) => { + PopulationMode::KernelDefaultOpportunistic + } + (ThpEnabled::Madvise, ThpDefrag::Madvise | ThpDefrag::DeferPlusMadvise) => { + PopulationMode::AdaptiveHugepage { + fallback_needs_nohugepage: false, + } + } + _ => PopulationMode::AdaptiveHugepage { + fallback_needs_nohugepage: true, + }, + }; + assert_eq!( + select_population_mode(enabled, defrag, pmd), + expected, + "enabled={enabled:?}, defrag={defrag:?}" + ); + } + } + } + + #[test] + fn buddyinfo_parser_weights_higher_orders_handles_zones_and_saturates_overflow() { + let two_numa = "\ +Node 0, zone DMA 1 0 0 0 0 0 0 0 0 5 3 +Node 0, zone DMA32 100 50 20 10 5 2 1 1 1 9 4 +Node 0, zone Normal 1000 500 200 100 50 20 10 5 2 3 4 +Node 1, zone Normal 800 400 150 80 40 15 8 4 1 0 2 +Node 1, zone Movable 0 0 0 0 0 0 0 0 0 1 1 +"; + // For 4 KiB base pages and 2 MiB PMD (order 9): + // Node 0 Normal: 3*1 + 4*2 = 11; Node 1 Normal: 0*1 + 2*2 = 4; Node 1 Movable: 1*1 + 1*2 = 3. + // DMA and DMA32 are excluded when Normal/Movable exist. + assert_eq!( + parse_buddyinfo_free_hugepages(two_numa, 2 << 20, 4096), + Some(18) + ); + + // NUMA mems_allowed filtering restricts summing to allowed nodes only. + let node0_only = parse_mems_allowed_list("Name:\ttest\nMems_allowed_list:\t0\n").unwrap(); + assert_eq!(node0_only, vec![(0, 0)]); + assert_eq!( + parse_buddyinfo_free_hugepages_for_nodes(two_numa, 2 << 20, 4096, Some(&node0_only)), + Some(11) + ); + let node1_only = parse_mems_allowed_list("Mems_allowed_list:\t1\n").unwrap(); + assert_eq!( + parse_buddyinfo_free_hugepages_for_nodes(two_numa, 2 << 20, 4096, Some(&node1_only)), + Some(7) + ); + assert_eq!( + parse_mems_allowed_list("Mems_allowed_list:\t0-1,3\n"), + Some(vec![(0, 1), (3, 3)]) + ); + assert_eq!(parse_mems_allowed_list("Mems_allowed_list:\t2-1\n"), None); + assert_eq!(parse_mems_allowed_list("Name:\tno_field\n"), None); + + // Small ARM64 SoC without Normal or Movable zones falls back to all zones. + let dma_only = "Node 0, zone DMA32 10 9 8 7 6 5 4 3 2 1 2 3\n"; + // Order 9: 1*1, order 10: 2*2, order 11: 3*4 => 1 + 4 + 12 = 17. + assert_eq!( + parse_buddyinfo_free_hugepages(dma_only, 2 << 20, 4096), + Some(17) + ); + + // 16 KiB base pages, 32 MiB PMD => order 11. + assert_eq!( + parse_buddyinfo_free_hugepages(dma_only, 32 << 20, 16384), + Some(3) + ); + + // 64 KiB base pages, 512 MiB PMD => order 13. + let arm64_64k = "Node 0, zone Normal 0 0 0 0 0 0 0 0 0 0 0 0 0 5 2\n"; + assert_eq!( + parse_buddyinfo_free_hugepages(arm64_64k, 512 << 20, 65536), + Some(5 + 2 * 2) + ); + + // Overflow saturation on high orders and huge counts. + let mut high_orders = String::from("Node 0, zone Normal"); + for _ in 0..80 { + high_orders.push_str(" 0"); + } + high_orders.push_str(" 2\n"); + assert_eq!( + parse_buddyinfo_free_hugepages(&high_orders, 2 << 20, 4096), + Some(u64::MAX) + ); + + // Unparseable / empty content or invalid sizes return None. + assert_eq!(parse_buddyinfo_free_hugepages("", 2 << 20, 4096), None); + assert_eq!( + parse_buddyinfo_free_hugepages("not buddyinfo\n", 2 << 20, 4096), + None + ); + assert_eq!(parse_buddyinfo_free_hugepages(two_numa, 4096, 4096), None); + assert_eq!(parse_buddyinfo_free_hugepages(two_numa, 3 << 20, 4096), None); + } + + #[test] + fn vmstat_parser_extracts_compact_stall_and_rejects_malformed_lines() { + let vmstat = "\ +nr_free_pages 123456 +compact_stall 42 +compact_fail 7 +"; + assert_eq!(parse_vmstat_counter(vmstat, "compact_stall"), Some(42)); + assert_eq!(parse_vmstat_counter(vmstat, "compact_fail"), Some(7)); + assert_eq!(parse_vmstat_counter(vmstat, "missing"), None); + assert_eq!( + parse_vmstat_counter("compact_stall 42 extra\n", "compact_stall"), + None + ); + assert_eq!( + parse_vmstat_counter("compact_stall nope\n", "compact_stall"), + None + ); + } + + #[test] + fn buddyinfo_reserve_and_stall_thresholds_match_bounds() { + assert_eq!(buddyinfo_required_hugepages(1, 1), 1); + assert_eq!(buddyinfo_required_hugepages(1, 16), 2); + assert_eq!(buddyinfo_required_hugepages(8, 512), 40); + assert_eq!(buddyinfo_required_hugepages(8, 60_000), 40); + + let (floor_2m, ceil_2m) = stall_thresholds(2 << 20); + assert_eq!(floor_2m, Duration::from_millis(15)); + assert_eq!(ceil_2m, Duration::from_millis(50)); + + let (floor_16m, ceil_16m) = stall_thresholds(16 << 20); + assert_eq!(floor_16m, Duration::from_micros(15_625)); + assert_eq!(ceil_16m, Duration::from_micros(62_500)); + + let (floor_512m, ceil_512m) = stall_thresholds(512 << 20); + assert_eq!(floor_512m, Duration::from_millis(500)); + assert_eq!(ceil_512m, Duration::from_millis(2_000)); + + assert_eq!( + classify_chunk_elapsed(floor_16m, 16 << 20), + ChunkStallCheck::Healthy + ); + assert_eq!( + classify_chunk_elapsed(floor_16m + Duration::from_nanos(1), 16 << 20), + ChunkStallCheck::CheckCompactStall + ); + assert_eq!( + classify_chunk_elapsed(ceil_16m, 16 << 20), + ChunkStallCheck::CheckCompactStall + ); + assert_eq!( + classify_chunk_elapsed(ceil_16m + Duration::from_nanos(1), 16 << 20), + ChunkStallCheck::Stalled + ); + } + + #[test] + fn parse_smaps_handles_merged_and_split_vmas() { + let sample = "\ +7f0000000000-7f0000600000 rw-p 00000000 00:00 0 +Size: 6144 kB +VmFlags: rd wr mr mw me ac nh sd +7f0000600000-7f0000800000 rw-p 00000000 00:00 0 +Size: 2048 kB +VmFlags: rd wr mr mw me ac hg sd +"; + // Lower-address merged VMA covers [0x7f0000200000, 0x7f0000600000). + let merged = parse_smaps_intersecting_vmas(sample, 0x7f00_0020_0000, 0x7f00_0060_0000); + assert_eq!(merged.len(), 1); + assert!(merged[0].start <= 0x7f00_0020_0000 && merged[0].end >= 0x7f00_0060_0000); + assert!( + merged[0] + .vm_flags + .as_ref() + .unwrap() + .iter() + .any(|flag| flag == "nh") + ); + + // A range spanning both entries reports two intersecting VMAs. + let split = parse_smaps_intersecting_vmas(sample, 0x7f00_0040_0000, 0x7f00_0080_0000); + assert_eq!(split.len(), 2); + } + #[test] fn map_host_advises_hugepages_and_prefaults_zeroed_pages() { let bytes = 4 << 20; @@ -212,38 +1186,168 @@ mod tests { assert!(slice.iter().all(|&b| b == 0)); #[cfg(target_os = "linux")] if let Ok(smaps) = std::fs::read_to_string("/proc/self/smaps") { - let needle = format!("{address:x}-"); - if let Some(start) = smaps.find(&needle) { - let block = &smaps[start..]; - let end = block[1..] - .find('\n') - .and_then(|first_nl| { - block[first_nl + 1..] - .lines() - .position(|line| { - line.as_bytes().first().is_some_and(u8::is_ascii_hexdigit) - && line.contains('-') - }) - .map(|idx| { - block[first_nl + 1..] - .lines() - .take(idx) - .map(|l| l.len() + 1) - .sum::() - + first_nl - + 1 - }) - }) - .unwrap_or(block.len()); - let vma = &block[..end]; - if let Some(flags) = vma.lines().find(|l| l.starts_with("VmFlags:")) { + let vmas = parse_smaps_intersecting_vmas(&smaps, address, address + bytes); + assert_eq!( + vmas.len(), + 1, + "expected a single VMA covering [{address:#x}, {:#x}), got: {vmas:?}", + address + bytes + ); + let vma = &vmas[0]; + assert!( + vma.start <= address && vma.end >= address + bytes, + "VMA [{:#x}, {:#x}) does not cover [{address:#x}, {:#x})", + vma.start, + vma.end, + address + bytes + ); + let thp_present = + std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/enabled").is_ok(); + if thp_present && let Some(flags) = &vma.vm_flags { + let policy = detect_thp_policy(); + match policy.mode { + PopulationMode::EagerHugepage => { + assert!( + flags.iter().any(|flag| flag == "hg"), + "expected MADV_HUGEPAGE (hg) in VmFlags, got: {flags:?}" + ); + } + PopulationMode::AdaptiveHugepage { + fallback_needs_nohugepage, + } => { + let hpage_size = policy.hpage_pmd_size.unwrap(); + let end = address + bytes; + let aligned_start = address.checked_next_multiple_of(hpage_size); + let aligned_end = (end / hpage_size) * hpage_size; + if aligned_start.is_none_or(|start| start >= aligned_end) { + if fallback_needs_nohugepage { + assert!( + flags.iter().any(|flag| flag == "nh"), + "expected MADV_NOHUGEPAGE (nh) in VmFlags, got: {flags:?}" + ); + } + } else if !(aligned_start == Some(address) + && aligned_end == end + && bytes == hpage_size + && !fallback_needs_nohugepage) + { + assert!( + flags.iter().any(|flag| flag == "hg" || flag == "nh"), + "expected hg or nh in VmFlags for adaptive mode, got: {flags:?}" + ); + } + } + PopulationMode::BasePages | PopulationMode::KernelDefaultOpportunistic => {} + } + } + } + unsafe { unmap_host(address, bytes) }; + } + + #[cfg(target_os = "linux")] + #[test] + fn adaptive_mid_mapping_fallback_merges_into_single_vma() { + let base_page = page_size().max(4096); + // Bound the test stride to 2 MiB so 64 KiB ARM64 kernels do not allocate > 1 GiB. + let stride = read_hpage_pmd_size(base_page) + .unwrap_or(2 << 20) + .min(2 << 20) + .max(base_page * 2); + let bytes = 4 * stride; + let thp_present = + std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/enabled").is_ok(); + + for fallback_needs_nohugepage in [false, true] { + let mut buddy_checks = 0usize; + let address = map_host_with(bytes, |guard| { + populate_adaptive_with( + guard.ptr().cast::(), + guard.bytes, + stride, + base_page, + fallback_needs_nohugepage, + || { + buddy_checks += 1; + if buddy_checks == 1 { + Some(u64::MAX) + } else { + Some(0) + } + }, + || Some(0), + ) + }) + .unwrap(); + assert!( + buddy_checks >= 2, + "expected at least one hugepage chunk followed by fallback, got {buddy_checks} checks" + ); + let slice = unsafe { std::slice::from_raw_parts(address as *const u8, bytes) }; + assert!(slice.iter().all(|&b| b == 0)); + + if let Ok(smaps) = std::fs::read_to_string("/proc/self/smaps") { + let vmas = parse_smaps_intersecting_vmas(&smaps, address, address + bytes); + assert_eq!( + vmas.len(), + 1, + "expected single merged VMA after fallback (fallback_needs_nohugepage={fallback_needs_nohugepage}), got: {vmas:?}" + ); + let vma = &vmas[0]; + assert!(vma.start <= address && vma.end >= address + bytes); + if thp_present && let Some(flags) = &vma.vm_flags { assert!( - flags.split_whitespace().any(|flag| flag == "hg"), - "expected MADV_HUGEPAGE (hg) in VmFlags, got: {flags}" + flags.iter().any(|flag| flag == "nh"), + "expected MADV_NOHUGEPAGE (nh) after mid-mapping fallback, got: {flags:?}" ); } } + unsafe { unmap_host(address, bytes) }; } - unsafe { unmap_host(address, bytes) }; + } + + #[cfg(target_os = "linux")] + #[test] + fn populate_linux_applies_eager_and_base_page_policies() { + let base_page = page_size().max(4096); + let bytes = 4 << 20; + let thp_present = + std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/enabled").is_ok(); + + let eager_policy = ThpPolicy { + page_size: base_page, + hpage_pmd_size: Some(2 << 20), + mode: PopulationMode::EagerHugepage, + }; + let eager_addr = + map_host_with(bytes, |guard| populate_linux(guard, &eager_policy)).unwrap(); + if let Ok(smaps) = std::fs::read_to_string("/proc/self/smaps") { + let vmas = parse_smaps_intersecting_vmas(&smaps, eager_addr, eager_addr + bytes); + assert_eq!(vmas.len(), 1); + if thp_present && let Some(flags) = &vmas[0].vm_flags { + assert!( + flags.iter().any(|f| f == "hg"), + "expected hg for EagerHugepage, got: {flags:?}" + ); + } + } + unsafe { unmap_host(eager_addr, bytes) }; + + let base_policy = ThpPolicy { + page_size: base_page, + hpage_pmd_size: None, + mode: PopulationMode::BasePages, + }; + let base_addr = map_host_with(bytes, |guard| populate_linux(guard, &base_policy)).unwrap(); + if let Ok(smaps) = std::fs::read_to_string("/proc/self/smaps") { + let vmas = parse_smaps_intersecting_vmas(&smaps, base_addr, base_addr + bytes); + assert_eq!(vmas.len(), 1); + if thp_present && let Some(flags) = &vmas[0].vm_flags { + assert!( + !flags.iter().any(|f| f == "hg" || f == "nh"), + "expected neither hg nor nh for BasePages, got: {flags:?}" + ); + } + } + unsafe { unmap_host(base_addr, bytes) }; } } diff --git a/helios/src/offload/mod.rs b/helios/src/offload/mod.rs index 6ff75244c..7cd992ddf 100644 --- a/helios/src/offload/mod.rs +++ b/helios/src/offload/mod.rs @@ -28,8 +28,8 @@ use flare_selene::{CacheGeometry, HostStore}; use crate::Result; pub use flare_selene::offload::{ - KvCompression, PrefixCacheOffload, Preparation, PrepareInputs, Prepared, Resolved, Shared, - input_memory_bytes, parse_drain_on_shutdown, parse_max_age, parse_size, + KvCompression, PrefixCacheOffload, Preparation, PrepareInputs, PrepareTimings, Prepared, + Resolved, Shared, input_memory_bytes, parse_drain_on_shutdown, parse_max_age, parse_size, }; #[derive(Clone, Debug)] @@ -87,7 +87,27 @@ pub fn prepare_with_inputs_budget( inputs: PrepareInputs, host_budget: Option, ) -> Result { - Ok(flare_selene::offload::prepare_with_inputs_budget( + prepare_with_inputs_budget_with_progress( + options, + identity, + geometry, + contexts, + inputs, + host_budget, + |_| {}, + ) +} + +pub fn prepare_with_inputs_budget_with_progress( + options: &PrefixCacheOffload, + identity: [u8; 32], + geometry: Vec, + contexts: Vec<(usize, i32)>, + inputs: PrepareInputs, + host_budget: Option, + on_step: impl FnMut(&str), +) -> Result { + Ok(flare_selene::offload::prepare_with_inputs_budget_with_progress( options, identity, geometry, @@ -95,6 +115,7 @@ pub fn prepare_with_inputs_budget( inputs, host_budget, ®istrar::CudaRegistrar, + on_step, )?) } diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index b9561b074..8a61b08c1 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -963,7 +963,7 @@ impl NativeModel { .as_ref() .map(|cluster| (cluster.rank, cluster.world)); let integrated = self.ranks.iter().any(|rank| rank.integrated); - let prepared = crate::offload::prepare_with_inputs_budget( + let prepared = crate::offload::prepare_with_inputs_budget_with_progress( &options.prefix_cache, identity, geometry, @@ -975,6 +975,7 @@ impl NativeModel { integrated, }, planned_host_budget, + |step| phase.detail(step), )?; phase.finish(self.attach_offload(prepared)?); Ok(()) diff --git a/selene/src/offload.rs b/selene/src/offload.rs index 6a15d2446..94ca4f8c5 100644 --- a/selene/src/offload.rs +++ b/selene/src/offload.rs @@ -10,7 +10,10 @@ use crate::{ CacheGeometry, HostStore, Layout, Result, composite, disk, disk_store, geometry, input, memory, pool, pool::PoolOptions, record, shard, slab, }; -use std::{path::PathBuf, time::Duration}; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; /// The host supplies CUDA copy engines after the final cache geometry is known. pub trait CopierFactory { @@ -325,6 +328,17 @@ pub struct PrepareInputs { pub integrated: bool, } +/// Elapsed durations for host prefix-cache startup sub-steps. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PrepareTimings { + /// Time spent allocating a split pool or populating a contiguous host slab. + pub slab_populate: Option, + /// Time spent registering a contiguous host slab with CUDA. + pub cuda_register: Option, + /// Time spent scanning existing disk records. + pub disk_scan: Option, +} + /// Host resources the loader prepares once per process and the model worker /// turns into a store: registered pools, the scanned record directory, and /// every rank's geometry and CUDA context. @@ -351,6 +365,7 @@ pub struct Prepared { pub pool: Option, pub drain_on_shutdown: Duration, pub max_age: Duration, + pub timings: PrepareTimings, } /// The loader's result: either prepared resources or the reason no store exists. @@ -400,8 +415,22 @@ impl Prepared { pub fn summary(&self) -> String { let mut parts = Vec::new(); if let Some(pool) = &self.memory_pool { + let mut details = vec![format!("{} slots", pool.slot_count())]; + if pool.rank_parts().is_some() { + details.push("split by rank".to_owned()); + if let Some(allocate) = self.timings.slab_populate { + details.push(format!("allocate {}", elapsed_seconds(allocate))); + } + } else { + if let Some(populate) = self.timings.slab_populate { + details.push(format!("populate {}", elapsed_seconds(populate))); + } + if let Some(register) = self.timings.cuda_register { + details.push(format!("register {}", elapsed_seconds(register))); + } + } parts.push(format!( - "{} {} ({} slots{})", + "{} {} ({})", if self.warm_bytes != 0 { "memory" } else if pool.intake_slots() == 0 { @@ -410,12 +439,7 @@ impl Prepared { "intake" }, gibibytes(pool.bytes()), - pool.slot_count(), - if pool.rank_parts().is_some() { - ", split by rank" - } else { - "" - } + details.join(", "), )); } else { let mode = if self.rank_process { @@ -433,17 +457,28 @@ impl Prepared { )); } if let Some(directory) = &self.resolved.directory { + let mut details = vec![ + format!("limit {}", gibibytes(self.resolved.disk_limit)), + format!("{} records", self.scanned.len()), + "staged".to_owned(), + ]; + if let Some(scan) = self.timings.disk_scan { + details.push(format!("scan {}", elapsed_seconds(scan))); + } parts.push(format!( - "disk {} (limit {}, {} records, staged)", + "disk {} ({})", directory.display(), - gibibytes(self.resolved.disk_limit), - self.scanned.len(), + details.join(", "), )); } parts.join(" · ") } } +fn elapsed_seconds(duration: Duration) -> String { + format!("{:.1}s", duration.as_secs_f64()) +} + pub fn gibibytes(bytes: u64) -> String { format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64) } @@ -536,6 +571,28 @@ pub fn prepare_with_inputs( } pub fn prepare_with_inputs_budget( + options: &PrefixCacheOffload, + identity: [u8; 32], + geometry: Vec, + contexts: Vec<(usize, i32)>, + inputs: PrepareInputs, + host_budget: Option, + registrar: &dyn crate::HostRegistrar, +) -> Result { + prepare_with_inputs_budget_with_progress( + options, + identity, + geometry, + contexts, + inputs, + host_budget, + registrar, + |_| {}, + ) +} + +#[allow(clippy::too_many_arguments)] +pub fn prepare_with_inputs_budget_with_progress( options: &PrefixCacheOffload, identity: [u8; 32], mut geometry: Vec, @@ -543,6 +600,7 @@ pub fn prepare_with_inputs_budget( inputs: PrepareInputs, host_budget: Option, registrar: &dyn crate::HostRegistrar, + mut on_step: impl FnMut(&str), ) -> Result { let PrepareInputs { max_active, @@ -623,44 +681,70 @@ pub fn prepare_with_inputs_budget( let checkpoint_memory = memory_bytes - input_memory; let local_pages = geometry.iter().map(|rank| rank.page_capacity).max().filter(|_| shard.is_none()); let capture = local_pages.is_some() && options.pool_only(); - let memory_pool = (capture || checkpoint_memory != 0 || directory.is_some()) - .then(|| { - let (_, host) = effective.headroom_inner( - contexts.len(), - &layout, - inputs, - local_pages, - host_budget, - )?; - let transfer_slots = (host - memory_bytes) / layout.page_record_bytes; - let intake = if capture { 0 } else { transfer_slots as usize }; - let bytes = (checkpoint_memory / layout.page_record_bytes + transfer_slots) * layout.page_record_bytes; - // Shared and compressed records must be readable by the CPU. - // Memory-only pools split by rank through HOST_NUMA VMM where the driver - // supports it, and fall back to a registered anonymous mapping on hosts - // without HOST_NUMA VMM (such as GA10B or Windows). - let pool = if directory.is_none() - && effective.pool.is_none() - && effective.compression == KvCompression::Off - { - match slab::SlabPool::try_sized_by_rank(&layout, bytes, intake, &contexts, registrar)? { - Some(pool) => pool, - None => { - let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?; - pool.register(registrar, context)?; - pool - } - } - } else { + let mut timings = PrepareTimings::default(); + let memory_pool = if capture || checkpoint_memory != 0 || directory.is_some() { + let (_, host) = effective.headroom_inner( + contexts.len(), + &layout, + inputs, + local_pages, + host_budget, + )?; + let transfer_slots = (host - memory_bytes) / layout.page_record_bytes; + let intake = if capture { 0 } else { transfer_slots as usize }; + let bytes = (checkpoint_memory / layout.page_record_bytes + transfer_slots) + * layout.page_record_bytes; + let size_label = gibibytes(bytes); + // Shared and compressed records must be readable by the CPU. + // Memory-only pools split by rank through HOST_NUMA VMM where the driver + // supports it, and fall back to a registered anonymous mapping on hosts + // without HOST_NUMA VMM (such as GA10B or Windows). + let split = if directory.is_none() + && effective.pool.is_none() + && effective.compression == KvCompression::Off + { + on_step(&format!("allocating {size_label} split host slab")); + let started = Instant::now(); + slab::SlabPool::try_sized_by_rank(&layout, bytes, intake, &contexts, registrar)? + .map(|pool| { + timings.slab_populate = Some(started.elapsed()); + pool + }) + } else { + None + }; + let pool = match split { + Some(pool) => pool, + None => { + on_step(&format!("populating {size_label} host slab")); + let started = Instant::now(); let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?; + timings.slab_populate = Some(started.elapsed()); + on_step(&format!("registering {size_label} host slab with CUDA")); + let started = Instant::now(); pool.register(registrar, context)?; + timings.cuda_register = Some(started.elapsed()); pool - }; - Ok::<_, crate::Error>(pool) - }) - .transpose()?; + } + }; + Some(pool) + } else { + None + }; let scanned = match &directory_lock { - Some(directory) => record::scan(directory, &identity, &fingerprint, geometry[0].page_tokens, &record::rank_sizes(&geometry))?, + Some(directory) => { + on_step("scanning disk records"); + let started = Instant::now(); + let records = record::scan( + directory, + &identity, + &fingerprint, + geometry[0].page_tokens, + &record::rank_sizes(&geometry), + )?; + timings.disk_scan = Some(started.elapsed()); + records + } None => Vec::new(), }; let disk_budget = input::DiskBudget::new(disk_limit, scanned.iter().map(|r| r.bytes).sum()); @@ -701,6 +785,7 @@ pub fn prepare_with_inputs_budget( directory_lock, shards: Vec::new(), pool: None, + timings, }))) } @@ -741,6 +826,7 @@ pub fn open(prepared: Prepared, factory: &dyn CopierFactory) -> Result, +} + +impl crate::SplitMapping for SyntheticSplitMapping { + fn address(&self) -> usize { + self.base + } + + fn nbytes(&self) -> usize { + self.nbytes + } + + fn part_address(&self, index: usize) -> usize { + self.base + self.part_offsets[index] + } +} + +struct SplitFixtureRegistrar; + +impl crate::HostRegistrar for SplitFixtureRegistrar { + fn register( + &self, + _context: usize, + _address: usize, + _bytes: usize, + ) -> Result> { + Err("contiguous registration should not run for a split pool".into()) + } + + fn map_split(&self, requests: &[(usize, i32, usize)]) -> Result> { + let mut offset = 0usize; + let mut part_offsets = Vec::with_capacity(requests.len()); + for &(_, _, bytes) in requests { + part_offsets.push(offset); + offset += bytes; + } + Ok(Box::new(SyntheticSplitMapping { + base: 0x4000_0000, + nbytes: offset, + part_offsets, + })) + } +} + +#[test] +fn prepare_reports_split_by_rank_timings_and_steps() { + let options = PrefixCacheOffload { + memory_bytes: Some(16 * 4096), + ..Default::default() + }; + let geometry = vec![crate::testing::geometry(64, &[("kv", 4096)], 4096)]; + let mut steps = Vec::new(); + let Preparation::Store(mut prepared) = super::prepare_with_inputs_budget_with_progress( + &options, + [0; 32], + geometry, + vec![(0, 0)], + inputs(1), + None, + &SplitFixtureRegistrar, + |step| steps.push(step.to_owned()), + ) + .unwrap() else { + panic!("missing memory store"); + }; + let (size, slot_count, has_rank_parts) = { + let pool = prepared.memory_pool.as_ref().unwrap(); + ( + gibibytes(pool.bytes()), + pool.slot_count(), + pool.rank_parts().is_some(), + ) + }; + assert!(has_rank_parts); + assert_eq!(steps, vec![format!("allocating {size} split host slab")]); + assert!(prepared.timings.slab_populate.is_some()); + assert!(prepared.timings.cuda_register.is_none()); + assert!(prepared.timings.disk_scan.is_none()); + + prepared.timings.slab_populate = Some(Duration::from_millis(1_200)); + assert_eq!( + prepared.summary(), + format!("memory {size} ({slot_count} slots, split by rank, allocate 1.2s)") + ); +} + +#[test] +fn prepare_reports_split_fallback_to_contiguous_timings_and_steps() { + let options = PrefixCacheOffload { + memory_bytes: Some(16 * 4096), + ..Default::default() + }; + let geometry = vec![crate::testing::geometry(64, &[("kv", 4096)], 4096)]; + let registrar = UnsupportedSplitRegistrar { + inner: crate::testing::TrackingRegistrar::default(), + split_error: None, + }; + let mut steps = Vec::new(); + let Preparation::Store(mut prepared) = super::prepare_with_inputs_budget_with_progress( + &options, + [0; 32], + geometry, + vec![(0, 0)], + inputs(1), + None, + ®istrar, + |step| steps.push(step.to_owned()), + ) + .unwrap() else { + panic!("missing memory store"); + }; + let (size, slot_count, has_rank_parts) = { + let pool = prepared.memory_pool.as_ref().unwrap(); + ( + gibibytes(pool.bytes()), + pool.slot_count(), + pool.rank_parts().is_some(), + ) + }; + assert!(!has_rank_parts); + assert_eq!( + steps, + vec![ + format!("allocating {size} split host slab"), + format!("populating {size} host slab"), + format!("registering {size} host slab with CUDA"), + ] + ); + assert!(prepared.timings.slab_populate.is_some()); + assert!(prepared.timings.cuda_register.is_some()); + assert!(prepared.timings.disk_scan.is_none()); + + prepared.timings = PrepareTimings { + slab_populate: Some(Duration::from_millis(2_400)), + cuda_register: Some(Duration::from_millis(700)), + disk_scan: None, + }; + assert_eq!( + prepared.summary(), + format!("memory {size} ({slot_count} slots, populate 2.4s, register 0.7s)") + ); +} + +#[test] +fn prepare_reports_contiguous_and_disk_timings_and_steps() { + let directory = test_directory(); + let options = PrefixCacheOffload { + memory_bytes: Some(16 * 4096), + disk: Some(directory.clone()), + disk_limit: Some(1 << 30), + ..Default::default() + }; + let geometry = vec![crate::testing::geometry(64, &[("kv", 4096)], 4096)]; + let mut steps = Vec::new(); + let Preparation::Store(mut prepared) = super::prepare_with_inputs_budget_with_progress( + &options, + [0; 32], + geometry, + vec![(0, 0)], + inputs(1), + None, + &crate::testing::IdentityRegistrar, + |step| steps.push(step.to_owned()), + ) + .unwrap() else { + panic!("missing composite store"); + }; + let (size, slot_count) = { + let pool = prepared.memory_pool.as_ref().unwrap(); + (gibibytes(pool.bytes()), pool.slot_count()) + }; + let record_dir = prepared + .resolved + .directory + .as_ref() + .unwrap() + .display() + .to_string(); + assert_eq!( + steps, + vec![ + format!("populating {size} host slab"), + format!("registering {size} host slab with CUDA"), + "scanning disk records".to_owned(), + ] + ); + assert!(prepared.timings.slab_populate.is_some()); + assert!(prepared.timings.cuda_register.is_some()); + assert!(prepared.timings.disk_scan.is_some()); + + prepared.timings = PrepareTimings { + slab_populate: Some(Duration::from_millis(12_300)), + cuda_register: Some(Duration::from_millis(4_800)), + disk_scan: Some(Duration::from_millis(900)), + }; + assert_eq!( + prepared.summary(), + format!( + "memory {size} ({slot_count} slots, populate 12.3s, register 4.8s) · disk {record_dir} (limit {}, 0 records, staged, scan 0.9s)", + gibibytes(1 << 30), + ) + ); + drop(prepared); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn prepare_restore_only_emits_no_steps_and_preserves_summary() { + let directory = test_directory(); + std::fs::create_dir_all(&directory).unwrap(); + let blocker = directory.join("not-a-directory"); + std::fs::write(&blocker, b"file").unwrap(); + + let degraded_options = PrefixCacheOffload { + memory_bytes: Some(0), + disk: Some(blocker.join("records")), + disk_limit: Some(1 << 30), + pool: Some(pool("unix:/run/selene.sock")), + ..Default::default() + }; + let mut steps = Vec::new(); + let Preparation::Store(degraded) = super::prepare_with_inputs_budget_with_progress( + °raded_options, + [0; 32], + vec![crate::testing::geometry(64, &[("kv", 4096)], 4096)], + vec![(0, 0)], + inputs(1), + None, + &crate::testing::IdentityRegistrar, + |step| steps.push(step.to_owned()), + ) + .unwrap() else { + panic!("missing degraded restore-only store"); + }; + assert!(steps.is_empty()); + assert_eq!(degraded.timings, PrepareTimings::default()); + assert_eq!( + degraded.summary(), + "no local prefix cache available: restores only" + ); + + let shard_options = PrefixCacheOffload { + pool: Some(pool("unix:/run/selene.sock")), + ..Default::default() + }; + let Preparation::Store(sharded) = super::prepare_with_inputs_budget_with_progress( + &shard_options, + [0; 32], + vec![crate::testing::geometry(64, &[("kv", 4096)], 4096)], + vec![(0, 0)], + PrepareInputs { + shard: Some((1, 2)), + ..inputs(1) + }, + None, + &crate::testing::IdentityRegistrar, + |step| steps.push(step.to_owned()), + ) + .unwrap() else { + panic!("missing sharded restore-only store"); + }; + assert!(steps.is_empty()); + assert_eq!(sharded.timings, PrepareTimings::default()); + assert_eq!( + sharded.summary(), + "pool only across rank processes: restores only" + ); + + std::fs::remove_dir_all(directory).unwrap(); +}