diff --git a/crates/metal2vulkan-runtime/src/idle_sweep.rs b/crates/metal2vulkan-runtime/src/idle_sweep.rs index 259952531..69316e7f9 100644 --- a/crates/metal2vulkan-runtime/src/idle_sweep.rs +++ b/crates/metal2vulkan-runtime/src/idle_sweep.rs @@ -14,9 +14,9 @@ //! call, however long that took (`tests::idle_sweep`). //! - **When.** Each block kept empty, each block made ahead and each object parked tells the //! sweep when it may go ([`Due::by`]). The thread waits until the earliest such moment, sweeps, -//! asks what comes due next and waits for that; with nothing due it waits with no timeout. It -//! sweeps at most once every [`EVERY`], so a program that parks objects every frame wakes it -//! once a second at most. +//! asks what comes due next and waits for that; with nothing due it waits with no timeout, but +//! for its looks at glibc's heap (below). It sweeps at most once every [`EVERY`], so a program +//! that parks objects every frame wakes it once a second at most. //! - **Bounded.** One thread a device, started by the device's first creation call that may wait //! (`Device::keep_room`), stopped and joined by the device's teardown before the teardown //! destroys the parked objects and frees the memory ([`IdleSweep::stop`]). @@ -26,6 +26,20 @@ //! thread, which paces its frees (`step_aside::pace`). //! - **A section of the exit guard** (`exit_guard.rs`): each sweep's Vulkan calls run in one; once //! the process exits, nothing is swept and the thread ends. +//! - **glibc's free heap** ([`HeapLook`]). glibc's `malloc` keeps what the process's threads free +//! as free heap, its pages resident, until something hands it back; a large making does +//! (`pipeline/compile_memory.rs`), and what a program's objects, its frames' records or its +//! smaller makings freed stayed. So the thread also looks at the heap every [`HEAP_EVERY`], +//! whether or not a sweep is due, and hands the free heap back (`malloc_trim`, counted in +//! `WorkCounts::heap_trims`) once it holds more than the floor (`compile_memory::FREE_FLOOR`, +//! 256 MiB) above the least free a look read since the last trim, at two looks in a row. glibc +//! still counts a trimmed chunk free, so the bytes free alone would trim again at every look; +//! above the least free since, the bytes freed came after the trim. Memory allocated and freed +//! again between two looks, in chunks a trim handed back, is not seen. The trade: what the +//! process allocates there next faults its pages in again, about 1 s per 3.5 GiB, and a device's +//! thread trims once every two looks at most; each look (`mallinfo2`) and each trim holds each +//! arena's lock while it walks the arena's free chunks. Only where the process's allocator is +//! glibc's (Linux, the GNU environment); elsewhere the thread looks at nothing. use crate::churn_counts::Recycled; use crate::device::functions::Functions; @@ -44,6 +58,41 @@ use std::time::{Duration, Instant}; /// (`memory.rs`'s `KEPT_SWEEP_EVERY`) and the recyclers' time (`recycle.rs`). pub(crate) const EVERY: Duration = Duration::from_secs(1); +/// How often the thread looks at glibc's heap ([`HeapLook`]): every 5 seconds. +pub(crate) const HEAP_EVERY: Duration = Duration::from_secs(5); + +/// What the thread's looks at glibc's heap read since its last trim (the module docs). +#[derive(Default)] +pub(crate) struct HeapLook { + /// The least bytes free a look read since the last trim, that trim's own look among them. + least_free: usize, + /// The previous look found more than the floor free above `least_free`. + freed: bool, +} + +impl HeapLook { + /// A look at a heap of `free` bytes free: whether to trim now, the second look in a row to + /// find more than the floor free above the least free since the last trim. + pub(crate) fn look(&mut self, free: usize) -> bool { + self.least_free = self.least_free.min(free); + let freed = free - self.least_free > crate::pipeline::compile_memory::FREE_FLOOR; + let trim = freed && self.freed; + self.freed = freed && !trim; + if trim { + self.least_free = free; + } + trim + } +} + +/// Why the thread woke, where it was not asked to stop. +enum Wake { + /// A sweep is due. + Sweep, + /// A look at glibc's heap is due ([`HEAP_EVERY`]). + Heap, +} + /// When the sweep is next due: told by what keeps something for a while (the memory, the /// recyclers' parks), read by the thread. #[derive(Default)] @@ -80,22 +129,27 @@ impl Due { self.wake.notify_one(); } - /// Wait until the sweep is due: `false` where the thread is asked to stop. - fn wait(&self) -> bool { + /// Wait until the sweep is due, or until `heap`, the next look at glibc's heap, where that + /// comes first; with no look to make (`None`), until the sweep alone. `None` where the thread + /// is asked to stop. + fn wait(&self, heap: Option) -> Option { let mut state = lock(&self.state); loop { if state.stopping { - return false; + return None; } let now = Instant::now(); - state = match state.at { - Some(at) if at <= now => { - state.at = None; - state.not_before = Some(now + EVERY); - return true; - } - Some(at) => { - let waited = self.wake.wait_timeout(state, at - now); + if state.at.is_some_and(|at| at <= now) { + state.at = None; + state.not_before = Some(now + EVERY); + return Some(Wake::Sweep); + } + if heap.is_some_and(|heap| heap <= now) { + return Some(Wake::Heap); + } + state = match state.at.into_iter().chain(heap).min() { + Some(until) => { + let waited = self.wake.wait_timeout(state, until - now); waited.unwrap_or_else(PoisonError::into_inner).0 } None => (self.wake.wait(state)).unwrap_or_else(PoisonError::into_inner), @@ -170,18 +224,34 @@ impl IdleSweep { } } -/// The thread's loop: a sweep each time one is due, until stopped or the process exits. +/// The thread's loop: a sweep each time one is due, and a look at glibc's heap every +/// [`HEAP_EVERY`] where the process's allocator is glibc's, until stopped or the process exits. fn run(due: &Due, swept: &SweepTargets) { - while due.wait() { + use crate::pipeline::compile_memory; + let mut heap = HeapLook::default(); + let mut next_look = compile_memory::heap_bytes().map(|_| Instant::now() + HEAP_EVERY); + while let Some(wake) = due.wait(next_look) { let Some(busy) = exit_guard::enter() else { return; }; - let next = sweep(swept, Instant::now()); - drop(busy); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - due.sweeps.fetch_add(1, Ordering::Relaxed); - if let Some(next) = next { - due.by(next); + match wake { + Wake::Heap => { + next_look = Some(Instant::now() + HEAP_EVERY); + if compile_memory::heap_bytes().is_some_and(|(_, free)| heap.look(free)) { + compile_memory::trim(); + swept.counts.heap_trimmed(); + } + drop(busy); + } + Wake::Sweep => { + let next = sweep(swept, Instant::now()); + drop(busy); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + due.sweeps.fetch_add(1, Ordering::Relaxed); + if let Some(next) = next { + due.by(next); + } + } } } } diff --git a/crates/metal2vulkan-runtime/src/pipeline/compile_memory.rs b/crates/metal2vulkan-runtime/src/pipeline/compile_memory.rs index 76dfee4db..f71376d40 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/compile_memory.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/compile_memory.rs @@ -39,6 +39,9 @@ //! where it would have reused the free heap; the floor spares makings that leave less. Only //! where the process's allocator is glibc's (Linux, the GNU environment): on any other nothing is //! called, and a host whose `malloc` is not glibc's sees no change. +//! - **And at idle** (`idle_sweep.rs`). Free heap no large making left (what a program's objects, +//! its frames' records or a smaller making's compile freed) is handed back by the device's idle +//! sweep's thread, which looks at glibc's heap every few seconds ([`heap_bytes`], [`trim`]). //! - **Stated by the memory log** ([`heap`]). Each line of `METAL2VULKAN_LOG_MEMORY`'s log //! (`memory_log.rs`) ends with glibc's heap as `mallinfo2` states it then and the trims the //! process made so far, so a resident set that grows and stays reads as free heap, heap in use, @@ -97,29 +100,56 @@ impl Drop for LargeMaking<'_> { } } -/// The `malloc_trim` calls the process's large makings made ([`return_free_heap`]), every -/// device's: the memory log's count ([`heap`]). `WorkCounts::heap_trims` counts a device's. +/// The `malloc_trim` calls the process made ([`trim`]: its large makings' and its devices' idle +/// sweeps'), every device's: the memory log's count ([`heap`]). `WorkCounts::heap_trims` counts a +/// device's. static TRIMS: AtomicU64 = AtomicU64::new(0); /// Hand glibc's free heap back to the system where it holds more than [`FREE_FLOOR`] bytes free, /// every arena's: whether it called `malloc_trim` (the module docs). -#[cfg(all(target_os = "linux", target_env = "gnu"))] fn return_free_heap() -> bool { - // SAFETY: no precondition. - let free = unsafe { libc::mallinfo2() }.fordblks; - if free <= FREE_FLOOR { - return false; + match heap_bytes() { + Some((_, free)) if free > FREE_FLOOR => { + trim(); + true + } + _ => false, } +} + +/// glibc's heap now, every arena's: its bytes in use and its bytes free (`mallinfo2`'s `uordblks` +/// and `fordblks`; it takes each arena's lock and walks its free chunks). `None` where the +/// process's allocator is not glibc's. +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub(crate) fn heap_bytes() -> Option<(usize, usize)> { + // SAFETY: no precondition. + let info = unsafe { libc::mallinfo2() }; + Some((info.uordblks, info.fordblks)) +} + +/// Nothing where the process's allocator is not glibc's (the module docs). +#[cfg(not(all(target_os = "linux", target_env = "gnu")))] +pub(crate) fn heap_bytes() -> Option<(usize, usize)> { + None +} + +/// Hand glibc's free heap back to the system (`malloc_trim(0)`: the pages of every arena's free +/// chunks), counted among the process's trims. glibc still counts a chunk handed back as free +/// (`fordblks`); its pages are gone, and what is allocated there next faults them in again. +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub(crate) fn trim() { // SAFETY: no precondition; it returns free pages only. unsafe { libc::malloc_trim(0) }; TRIMS.fetch_add(1, Ordering::Relaxed); - true } -/// glibc's heap now, every arena's, as `mallinfo2` states it, and the trims the process's large -/// makings made: the end of a memory log line (the module docs). `None` where the process's -/// allocator is not glibc's. `mallinfo2` takes each arena's lock and walks its free chunks, which -/// only the log, a default-off diagnostic, asks for. +/// Nothing where the process's allocator is not glibc's (the module docs). +#[cfg(not(all(target_os = "linux", target_env = "gnu")))] +pub(crate) fn trim() {} + +/// glibc's heap now, every arena's, as `mallinfo2` states it, and the trims the process made: the +/// end of a memory log line (the module docs). `None` where the process's allocator is not +/// glibc's. #[cfg(all(target_os = "linux", target_env = "gnu"))] pub(crate) fn heap() -> Option { // SAFETY: no precondition. @@ -140,12 +170,6 @@ pub(crate) fn heap() -> Option { None } -/// Nothing where the process's allocator is not glibc's (the module docs). -#[cfg(not(all(target_os = "linux", target_env = "gnu")))] -fn return_free_heap() -> bool { - false -} - /// The words a making holds, given back when dropped. pub(crate) struct Words<'a> { limit: &'a Limit, diff --git a/crates/metal2vulkan-runtime/src/tests/idle_heap_look.rs b/crates/metal2vulkan-runtime/src/tests/idle_heap_look.rs new file mode 100644 index 000000000..9f9cf3376 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/idle_heap_look.rs @@ -0,0 +1,45 @@ +//! The idle sweep's looks at glibc's heap (`idle_sweep.rs`'s `HeapLook`): a trim at the second +//! look in a row that finds more than the floor (`compile_memory::FREE_FLOOR`) free above the +//! least free a look read since the last trim, and none for the free heap a trim left, which +//! glibc still counts free. + +use crate::idle_sweep::HeapLook; +use crate::pipeline::compile_memory::FREE_FLOOR; + +const MIB: usize = 1 << 20; + +/// Whether each look of one sweep's thread at `free` bytes free, one after another, trims. +fn looks(free: &[usize]) -> Vec { + let mut heap = HeapLook::default(); + free.iter().map(|&free| heap.look(free)).collect() +} + +#[test] +fn free_heap_past_the_floor_is_trimmed_at_the_second_look() { + let past = FREE_FLOOR + MIB; + // Trimmed at the second look, and not again while it stays as the trim left it. + assert_eq!(looks(&[past; 5]), [false, true, false, false, false]); + // The floor itself is kept. + assert_eq!(looks(&[FREE_FLOOR; 4]), [false; 4]); + // Past the floor at no two looks in a row: allocated again in between. + assert_eq!(looks(&[past, 0, past, 0]), [false; 4]); +} + +#[test] +fn free_heap_freed_after_a_trim_is_trimmed_again() { + let left = 1024 * MIB; + // Allocated from the chunks the trim handed back, then freed again: trimmed again. + assert_eq!( + looks(&[left, left, MIB, left, left]), + [false, true, false, false, true] + ); + // The heap grew past what the trim left free, then let go of it: trimmed again. + let more = left + FREE_FLOOR + MIB; + assert_eq!(looks(&[left, left, more, more]), [false, true, false, true]); + // Grew by the floor or less: kept. + let floor_more = left + FREE_FLOOR; + assert_eq!( + looks(&[left, left, floor_more, floor_more]), + [false, true, false, false] + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/idle_heap_trim.rs b/crates/metal2vulkan-runtime/src/tests/idle_heap_trim.rs new file mode 100644 index 000000000..277c0e647 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/idle_heap_trim.rs @@ -0,0 +1,80 @@ +//! The free heap a program's threads leave is handed back while the device is idle +//! (`idle_sweep.rs`'s `HeapLook`). With the device's idle sweep running (from its first buffer), +//! the test's thread allocates [`CHUNKS`] chunks of [`CHUNK`] bytes, writes each, and frees all but +//! one in every [`KEPT`] and the last: glibc keeps the freed chunks as free heap between live +//! ones, resident, which no free hands back. With no large making and nothing else of the +//! program's, the device's thread trims (`WorkCounts::heap_trims`) within [`IDLE`] and the +//! process's resident set falls by [`HANDED_BACK_MIB`] or more. Without the idle sweep's look at +//! the heap, nothing trims it and the resident set stays. +//! +//! A device test of glibc's allocator: compiled only under the validation crate's GPU safety cfgs +//! (`m2v_gpu`, `m2v_cpu_icd`), on Linux with the GNU environment, on the kind of device the cfg +//! selects. + +use super::blit_holds::{device, Scratch}; +use super::spares_bench::process_memory; +use crate::idle_sweep::HEAP_EVERY; +use crate::ResourceOptions; +use std::time::{Duration, Instant}; + +/// Each chunk's bytes: 64 KiB, under the least size glibc maps a chunk apart at (128 KiB). +const CHUNK: usize = 64 << 10; + +/// The chunks: 768 MiB. +const CHUNKS: usize = 12_288; + +/// One chunk in every so many stays live, so the freed ones lie between live chunks. +const KEPT: usize = 16; + +/// The least the resident set falls by, in MiB, of the 720 MiB freed. +const HANDED_BACK_MIB: u64 = 512; + +/// The longest the device may take, idle, to trim: six looks, two of them due, with room for a +/// loaded host. +const IDLE: Duration = Duration::from_secs(6 * HEAP_EVERY.as_secs()); + +/// The process's resident set, in MiB. +fn resident_mib() -> u64 { + process_memory()["vm-rss"] / 1024 +} + +#[test] +fn an_idle_device_hands_back_the_free_heap() { + let scratch = Scratch::new("idle-heap-trim"); + let device = device(&scratch.0); + // The device's first creation call that may wait starts its idle sweep (`Device::keep_room`). + let buffer = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let trims = || device.work_counts().heap_trims; + let before = trims(); + let mut chunks: Vec> = (0..CHUNKS).map(|i| vec![i as u8 | 1; CHUNK]).collect(); + let allocated = resident_mib(); + let mut at = 0; + chunks.retain(|_| { + let kept = at % KEPT == 0 || at == CHUNKS - 1; + at += 1; + kept + }); + let freed = resident_mib(); + let idle = Instant::now(); + while trims() == before && idle.elapsed() < IDLE { + std::thread::sleep(Duration::from_millis(200)); + } + let handed_back = resident_mib(); + println!( + "IDLE-HEAP-TRIM {}: resident {allocated} MiB with the chunks, {freed} after freeing, \ + {handed_back} after {:.1} s idle; {} trims", + device.name(), + idle.elapsed().as_secs_f64(), + trims() - before + ); + assert!( + trims() > before, + "{:.1} s idle, the device's thread did not hand the free heap back", + idle.elapsed().as_secs_f64() + ); + assert!( + freed >= handed_back + HANDED_BACK_MIB, + "the resident set fell from {freed} MiB to {handed_back} only" + ); + drop((chunks, buffer)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index a3405e790..656d5d81e 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -337,6 +337,9 @@ mod icon_coverage; mod icon_levels; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod icon_mips; +mod idle_heap_look; +#[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux", target_env = "gnu"))] +mod idle_heap_trim; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod idle_sweep; mod image_barriers; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 25051e7d7..b65143443 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -5651,11 +5651,13 @@ pub struct WorkCounts { pub makings_held_for_compile_memory: u64, /// The time those makings waited, in nanoseconds, summed. pub compile_memory_held_nanos: u64, - /// Large makings (65,536 SPIR-V words or more) whose return left glibc's `malloc` more than - /// 256 MiB of free heap, which the making's thread then handed back to the system with - /// `malloc_trim` (`pipeline/compile_memory.rs`): glibc keeps what a driver's compile frees in - /// the compiling thread's arena. Always 0 where the process's allocator is not glibc's (Linux, - /// the GNU environment). No Metal counterpart. + /// The times glibc's free heap was handed back to the system with `malloc_trim`: by a large + /// making (65,536 SPIR-V words or more) whose return left glibc's `malloc` more than 256 MiB + /// of free heap (`pipeline/compile_memory.rs`: glibc keeps what a driver's compile frees in + /// the compiling thread's arena), and by the device's idle sweep, once the heap held more + /// than 256 MiB free above the least free it read since the last trim, at two of its looks in + /// a row, 5 s apart (`idle_sweep.rs`). Always 0 where the process's allocator is not glibc's + /// (Linux, the GNU environment). No Metal counterpart. pub heap_trims: u64, /// The runs again of predicated loops' layings that a check submitted, the loop still running /// past its copies (`command_buffer/rerun.rs`). diff --git a/docs/API.md b/docs/API.md index 2b47e9f6c..cbd8e3a8b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1886,8 +1886,9 @@ bytes, block and memory type; and each copy of a no-copy object's host pages (`c as it is made and as it goes: the caller's pointer and length and the copy's host address, the two ranges the runtime's comparisons write on the CPU. On Linux with glibc's allocator each line ends with glibc's heap then, every arena's (`mallinfo2`: bytes in use, bytes free, what its arenas -hold, what it mapped apart) and the `malloc_trim` calls the process's large pipeline makings made, -so a resident set that grows and stays reads as free heap, heap in use, or neither. +hold, what it mapped apart) and the `malloc_trim` calls the process made (after its large pipeline +makings, and at its devices' idle sweeps once more than 256 MiB of free heap came since the last +trim), so a resident set that grows and stays reads as free heap, heap in use, or neither. With `METAL2VULKAN_LOG_SHADOWS` set, a device logs one line per shadow it makes of a texture (id name `metal2vulkan-shadows`, `Info` severity): the call (an IOSurface plane's among them, or the binding's or pass's call for a shadow made at its first use), the texture's format, size, levels