diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 50a5721ca..433067a66 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -140,8 +140,11 @@ pub(crate) enum C { TwinToDepthBytes, TwinToTwin, TwinToTwinBytes, + /// Pages a take left open and changed because the title wrote them in + /// frame after frame (`VICTORY_HOT_PAGES=1`). + HotKept, } -const COUNTERS: usize = C::TwinToTwinBytes as usize + 1; +const COUNTERS: usize = C::HotKept as usize + 1; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -328,7 +331,7 @@ pub(crate) fn log(frames: f64) { {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ unchanged; {:.1} fallbacks ({:.1} ms); {:.0} guard faults; textures {:.1} MB watched and \ changed, {:.1} MB hashed, {:.1} MB of them changed; watch time: kernel {:.1} ms, view queries {:.1} ms, protecting {:.1} ms; copied whole (not tracked) {:.1} MB in {:.1} ms; snapshots {:.1} MB in {:.1} ms; page faults {:.0} preparing, {:.0} copying back; {:.0} tracked pages marked through another mapping; \ - guards: {:.2} ms in the handler, {:.0} protect calls for {:.0} pages, {:.0} pages opened; \ + guards: {:.2} ms in the handler, {:.0} protect calls for {:.0} pages, {:.0} pages opened, {:.0} hot pages left open; \ {:.0} tracked pages written ({:.0} of them the frame before too); change checks: {:.1} ms \ asking for other mappings, {:.1} ms waiting for the guard lock; preparing: {:.1} ms in \ refresh batches, steps (each with the batch it flushes): refresh {:.1} ms, copy {:.1} ms, \ @@ -374,6 +377,7 @@ pub(crate) fn log(frames: f64) { c[C::ProtectCalls as usize], c[C::ProtectPages as usize], c[C::OpenPages as usize], + c[C::HotKept as usize], c[C::WrittenPages as usize], c[C::WrittenAgain as usize], ms(c[C::AliasUs as usize]), diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4c8e1bfac..5cfdcba76 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5805,6 +5805,7 @@ impl Meter { tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); self.frames += 1; crate::memory::log_frame(); + crate::watch::frame_presented(); #[cfg(feature = "diagnostics")] crate::watch::frame_done(); let next = FrameWindow { diff --git a/crates/victory-gpu/src/hot_pages.rs b/crates/victory-gpu/src/hot_pages.rs new file mode 100644 index 000000000..c726a7bcc --- /dev/null +++ b/crates/victory-gpu/src/hot_pages.rs @@ -0,0 +1,242 @@ +//! Pages the title writes in frame after frame, left open (opt-in, +//! `VICTORY_HOT_PAGES=1`). +//! +//! Guarding a tracked page costs a `VirtualProtect` when a tracker takes it, +//! and the title's first write to it after that costs a fault and another +//! `VirtualProtect` to open it again. Under Wine on Rosetta each costs a +//! Wine call under its one memory lock. On a 16 GB M1 Pro in the world that +//! was 545 ms of protecting (2,295 calls for 3,981 pages) and 235 ms in the +//! guard handler (1,480 pages opened) per frame, while 625 of the 1,166 +//! tracked pages written in a frame had been written the frame before too +//! (#554). For a page written in every frame, the guard saves nothing: the +//! tracker takes the page again anyway. +//! +//! [`Hot`] counts, per page, the frames in a row in which a guarded write +//! opened it. From [`STREAK`] frames on, the page is hot for [`HOLD`] +//! frames: a take leaves it open and changed, so the trackers holding it +//! copy it at every use without a guard or a fault. After the hold the +//! page is guarded again and has to earn its streak anew, so a page that +//! went quiet costs at most [`HOLD`] frames of copies. +//! +//! Only pages that no host buffer copy holds are left open: a buffer copy's +//! copy-back of shader writes needs the page's bytes from the title's first +//! write after the take, which only the guard's fault saves +//! (`crate::watch::Tracked::saved`). +//! +//! Plain std and no Windows calls, so its tests run everywhere. + +use std::collections::BTreeMap; + +/// Frames in a row a page must be written in before it is left open. +pub(crate) const STREAK: u32 = 3; +/// Frames a hot page stays open before it is guarded again. +pub(crate) const HOLD: u64 = 30; + +/// Whether hot pages are left open: `VICTORY_HOT_PAGES=1` (off by default). +#[cfg(windows)] +pub(crate) fn enabled() -> bool { + static ON: std::sync::LazyLock = + std::sync::LazyLock::new(|| crate::switch::on("VICTORY_HOT_PAGES")); + #[cfg(test)] + if FORCED.with(std::cell::Cell::get) { + return true; + } + *ON +} + +#[cfg(all(windows, test))] +thread_local! { + /// The switch, on for one test's thread (its takes, its faults and its + /// frames) and no other test's. + static FORCED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Turns the switch on for this thread (tests). +#[cfg(all(windows, test))] +pub(crate) fn force_on_this_thread() { + FORCED.with(|f| f.set(true)); +} + +#[derive(Clone, Copy)] +struct Page { + /// The last frame a guarded write opened the page in. + last: u64, + /// Frames in a row, up to `last`, a guarded write opened it in. + streak: u32, + /// The page is hot (left open) while the frame is before this. + until: u64, +} + +/// Write streaks of tracked pages, by page number. +#[derive(Default)] +pub(crate) struct Hot { + frame: u64, + pages: BTreeMap, +} + +impl Hot { + pub(crate) const fn new() -> Self { + Self { + frame: 0, + pages: BTreeMap::new(), + } + } + + /// A guarded write opened page `page` in the current frame. + pub(crate) fn written(&mut self, page: usize) { + let frame = self.frame; + let p = self.pages.entry(page).or_insert(Page { + last: frame, + streak: 0, + until: 0, + }); + if p.streak > 0 && p.last == frame { + return; + } + p.streak = if p.streak > 0 && p.last + 1 == frame { + p.streak + 1 + } else { + 1 + }; + p.last = frame; + if p.streak >= STREAK { + p.until = frame + HOLD; + } + } + + /// Whether page `page` is to be left open now. + pub(crate) fn is_hot(&self, page: usize) -> bool { + self.pages.get(&page).is_some_and(|p| self.frame < p.until) + } + + /// A frame was presented. Forgets pages neither hot nor written in the + /// frame that just ended, so the map holds only pages written lately. + pub(crate) fn frame_done(&mut self) { + let ended = self.frame; + self.frame += 1; + let now = self.frame; + self.pages.retain(|_, p| now < p.until || p.last >= ended); + } + + /// Pages hot now. + #[cfg(test)] + fn hot_count(&self) -> usize { + self.pages.values().filter(|p| self.frame < p.until).count() + } +} + +#[cfg(test)] +mod tests { + use super::{HOLD, Hot, STREAK}; + + /// `frames` frames, each with a guarded write to `page` unless the page + /// is left open then (hot pages take no faults). + fn write_every_frame(hot: &mut Hot, page: usize, frames: u64) { + for _ in 0..frames { + if !hot.is_hot(page) { + hot.written(page); + } + hot.frame_done(); + } + } + + #[test] + fn a_page_written_in_streak_frames_in_a_row_is_left_open() { + let mut hot = Hot::new(); + for _ in 0..STREAK - 1 { + hot.written(7); + hot.frame_done(); + assert!(!hot.is_hot(7), "not before {STREAK} frames in a row"); + } + hot.written(7); + assert!(hot.is_hot(7), "hot from the frame of its {STREAK}th write"); + hot.frame_done(); + assert!(hot.is_hot(7)); + assert_eq!(hot.hot_count(), 1); + } + + #[test] + fn several_writes_in_one_frame_count_once() { + let mut hot = Hot::new(); + for _ in 0..10 { + hot.written(3); + } + assert!(!hot.is_hot(3)); + hot.frame_done(); + hot.written(3); + assert!(!hot.is_hot(3)); + } + + #[test] + fn a_frame_without_a_write_breaks_the_streak() { + let mut hot = Hot::new(); + for _ in 0..STREAK - 1 { + hot.written(1); + hot.frame_done(); + } + hot.frame_done(); + hot.written(1); + assert!(!hot.is_hot(1), "streak restarted"); + for _ in 0..STREAK - 2 { + hot.frame_done(); + hot.written(1); + } + assert!(!hot.is_hot(1)); + hot.frame_done(); + hot.written(1); + assert!(hot.is_hot(1)); + } + + #[test] + fn a_hot_page_is_guarded_again_after_the_hold_and_relearns() { + let mut hot = Hot::new(); + write_every_frame(&mut hot, 9, u64::from(STREAK)); + assert!(hot.is_hot(9)); + // Written in every frame of the hold, unseen: no faults while open. + for _ in 1..HOLD { + assert!(hot.is_hot(9)); + hot.frame_done(); + } + assert!(!hot.is_hot(9), "guarded again after {HOLD} frames"); + // Still written every frame: back to hot after a new streak. + write_every_frame(&mut hot, 9, u64::from(STREAK) - 1); + assert!(!hot.is_hot(9)); + hot.written(9); + assert!(hot.is_hot(9)); + } + + #[test] + fn quiet_pages_are_forgotten() { + let mut hot = Hot::new(); + hot.written(1); + write_every_frame(&mut hot, 2, u64::from(STREAK)); + hot.frame_done(); + assert_eq!(hot.pages.len(), 1, "only the hot page is kept"); + for _ in 0..HOLD { + hot.frame_done(); + } + assert!(hot.pages.is_empty()); + assert_eq!(hot.hot_count(), 0); + } + + #[test] + fn steady_writes_fault_in_few_frames() { + // A page written in every one of 1,000 frames faults only in the + // frames it is guarded: STREAK of every STREAK + HOLD - 1. + let mut hot = Hot::new(); + let mut faults = 0; + for _ in 0..1000 { + if !hot.is_hot(5) { + hot.written(5); + faults += 1; + } + hot.frame_done(); + } + let cycle = u64::from(STREAK) + HOLD - 1; + assert!( + faults <= 1000 / cycle * u64::from(STREAK) + u64::from(STREAK), + "{faults} faults" + ); + assert!(faults < 150, "{faults} faults instead of 1,000"); + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index c7e8357b3..7695e7d43 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -58,6 +58,9 @@ pub mod fence; pub mod frame; #[cfg(windows)] mod heap_worker; +// Plain std, so its tests run everywhere. +#[cfg(any(windows, test))] +mod hot_pages; #[cfg(any(windows, test))] mod hdr_probe; mod hold; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 7456c44ff..af072837b 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -311,6 +311,9 @@ struct Guards { /// with no question to the runtime (whose lock its page mappings hold /// for long). alias_of: BTreeMap>, + /// Pages written in frame after frame, left open by takes when + /// `VICTORY_HOT_PAGES=1` ([`crate::hot_pages`]). + hot: crate::hot_pages::Hot, /// Tracked pages written this frame and the frame before (diagnostics). #[cfg(feature = "diagnostics")] written: BTreeSet, @@ -326,6 +329,7 @@ static GUARDS: Mutex = Mutex::new(Guards { holders: BTreeMap::new(), busy: Vec::new(), alias_of: BTreeMap::new(), + hot: crate::hot_pages::Hot::new(), #[cfg(feature = "diagnostics")] written: BTreeSet::new(), #[cfg(feature = "diagnostics")] @@ -961,12 +965,14 @@ impl Tracked { .filter(|p| !taken.contains(p)) .collect(); // Partial pages are copied but stay dirty for a later request. + // So are hot pages (`VICTORY_HOT_PAGES`): copied, not guarded. let whole: Vec = pages .iter() .copied() .filter(|&p| { (p * PAGE).max(self.start) >= from && ((p + 1) * PAGE).min(self.end) <= to }) + .filter(|&p| !left_open(&g, p)) .collect(); protect_with_aliases(&mut g, &whole, &others, true, Some(&mut unmapped), |pages| { let mut changed = self.changed.0.lock().unwrap_or_else(|e| e.into_inner()); @@ -1596,6 +1602,32 @@ fn mark_changed(g: &mut Guards, first: usize, last: usize, save: bool) { } } +/// Whether a take leaves page `page` open and changed instead of guarding +/// it: it is hot ([`crate::hot_pages`]) and no host buffer copy holds it, +/// since a buffer copy's copy-back needs the bytes its guard's fault saves. +fn left_open(g: &Guards, page: usize) -> bool { + if !crate::hot_pages::enabled() || !g.hot.is_hot(page) { + return false; + } + let open = g + .holders + .get(&page) + .is_some_and(|holders| holders.iter().all(|c| !c.3)); + #[cfg(feature = "diagnostics")] + if open { + crate::copystat::add(crate::copystat::C::HotKept, 1); + } + open +} + +/// At each presented frame: moves the hot pages' streaks on a frame, when +/// `VICTORY_HOT_PAGES=1`. +pub(crate) fn frame_presented() { + if crate::hot_pages::enabled() { + guards().hot.frame_done(); + } +} + /// At each presented frame (diagnostics): counts the tracked pages written /// in it, and those written the frame before too. #[cfg(feature = "diagnostics")] @@ -1930,6 +1962,9 @@ fn handle_write_fault(at: usize) -> bool { } } if changed(&mut g, page, page + 1, true) { + if crate::hot_pages::enabled() { + g.hot.written(page); + } drop(g); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::GuardFaults, 1); @@ -2187,6 +2222,53 @@ pub(crate) mod tests { unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; } + #[test] + fn pages_written_every_frame_are_left_open_unless_a_buffer_copy_holds_them() { + use crate::hot_pages::{HOLD, STREAK}; + crate::hot_pages::force_on_this_thread(); + let p = pool(2); + let tex = track(p, 2 * PAGE, true).expect("pool memory is tracked"); + let copy = track_copy(p + PAGE, PAGE, true).expect("tracked"); + assert_eq!(tex.take(p, p + 2 * PAGE), [(p, p + 2 * PAGE)]); + assert_eq!(copy.take(p, p + 2 * PAGE), [(p + PAGE, p + 2 * PAGE)]); + for _ in 0..STREAK { + // SAFETY: committed pages of ours; a guarded one faults and the + // handler opens it. + unsafe { + (p as *mut u8).write_volatile(1); + ((p + PAGE) as *mut u8).write_volatile(1); + } + assert_eq!(tex.take(p, p + 2 * PAGE), [(p, p + 2 * PAGE)]); + assert_eq!(copy.take(p, p + 2 * PAGE), [(p + PAGE, p + 2 * PAGE)]); + frame_presented(); + } + // The first page, held by the texture's tracker alone, is hot: left + // open and changed, so every take copies it. The second, which a + // buffer copy holds, is guarded as before. + assert!(writable(p), "hot page left open"); + assert!(read_only(p + PAGE), "a buffer copy's page stays guarded"); + assert!(tex.changed(p / PAGE) && !tex.changed(p / PAGE + 1)); + assert!(copy.clean()); + assert_eq!(tex.take(p, p + 2 * PAGE), [(p, p + PAGE)]); + assert_eq!( + tex.take(p, p + 2 * PAGE), + [(p, p + PAGE)], + "copied at every take" + ); + // SAFETY: open, so no fault: the tracker has the page changed anyway. + unsafe { (p as *mut u8).write_volatile(2) }; + assert!(tex.changed(p / PAGE)); + // After the hold the page is guarded again by the next take. + for _ in 0..HOLD { + frame_presented(); + } + assert_eq!(tex.take(p, p + 2 * PAGE), [(p, p + PAGE)]); + assert!(read_only(p), "guarded again after the hold"); + assert!(tex.take(p, p + 2 * PAGE).is_empty()); + drop((tex, copy)); + free(p); + } + #[test] fn writes_mark_every_tracker_of_their_page() { let p = pool(4); diff --git a/docs/macos.md b/docs/macos.md index 6cb110502..35aa11bea 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -294,6 +294,7 @@ None of these changes the default, except `VICTORY_OUTPUT`, which sets the title | `VICTORY_MAC_PRESSURE=0` | Stop reading the macOS kernel's memory pressure. By default, under Wine on macOS, host textures and idle host copies of title memory are also given up while the kernel warns of memory pressure, 1 % of the Mac's memory a frame (4 % while it is short), whatever Wine counts as free: Wine's free memory stayed above 17 % on a 24 GB Mac while macOS compressed 4 to 6 GB a second and swapped. | | `VICTORY_READ_STATS=1` | Logs the requests and bytes read from each file, every 30 seconds, for the 30 most read. It shows which files a slow share serves most, so you can copy those to fast local storage. | | `VICTORY_GPU_BUDGET_MB=` | Sets the budget that host textures are kept under, in place of the device's. | +| `VICTORY_HOT_PAGES=1` | With fault tracking on, stops guarding tracked pages that the title writes in frame after frame. After three frames in a row with a guarded write, a page is left open and copied at every use for 30 frames, then guarded again. That saves the `VirtualProtect` of each take and the fault and second `VirtualProtect` of the title's next write, each a Wine call under its memory lock (#554 measured 545 ms protecting and 235 ms in the guard handler per world frame on a 16 GB Mac, with more than half of the written pages written the frame before too). Pages that a host buffer copy holds are always guarded, because its copy-back of shader writes needs the bytes that the fault saves. A diagnostics build counts `hot pages left open` in its guards line. | | `VICTORY_PATCH_WIDE=` | Splits the 256-bit stores listed by `cargo xtask wide-stores` into 128-bit halves, so fault tracking does not stop Rosetta on them (see above). | | `VICTORY_PATCH_WIDE_DIR=` | The same for the title's DLLs: each DLL's list, made with `cargo xtask wide-stores` from its mapped image `/images/victory-image-<16 hex digits>.dll`, is read from `/.txt`. Series 1.0.2.1's ray-tracing structure builder DLL has 122 such stores, and with fault tracking on one of them stopped Rosetta in the world on an M1 Max (macOS 15.7.3) when only the executable's list was given. | | `VICTORY_MESH_OVER_LIMIT=1` | Makes mesh pipelines whose outputs remain over Metal's 32 KiB limit even after paired pruning and alignment repacking (refused under Wine by default, as they hang the queue; see above). |