From 2a1d681a445aa1b81e8900acba766b4469028692 Mon Sep 17 00:00:00 2001 From: = <=> Date: Tue, 1 Dec 2026 21:24:49 +0100 Subject: [PATCH] VICTORY_GUARD_LATER=1 (opt-in, with VICTORY_PORT_GUARD=1): written blocks are made read-only by a thread beside the askings A refresh asks what was written, guards it and copies it, on the threads the submitting thread waits for. Under Wine a change of protection is some 13 us with its one lock for all of memory held, and every other thread's wait behind it. A timeline of the prologue (RTX 5060, Proton) has 69 ms a frame of all threads' time in the refreshes of copies, 47 of it waiting for the guards' lock, which the title's write faults hold through a VirtualProtect as the refreshes do; all threads together wait 145 ms a frame for it. With port 6 the same time shows as VirtualProtect inside the refreshes: 51 and 20 ms a frame in two samples, 133 to 146 us a call. With the switch an asking changes no protection: - a block found written and open is told as written and named to a thread beside ("victory-guard"), which makes it and its pages' other views read-only a moment later and does not note it clean: what the title wrote between the asker's copy and the guard is in no copy yet; - the next asking finds it read-only and not clean, tells it as written once more and notes it clean, by the path that was there for a block made read-only for another view's sake; - a read-only block that is not clean and has a view still open (the title wrote through the other view) is named too, not covered by the asker. The thread takes the guards' lock shared for four blocks at a time: held for whole runs, the askings queued behind what takes the lock alone. It guards only what is still view memory, open, and neither left alone nor resting. What it costs is a second look at each written block. Measured (diagnostics timelines, port 6 without and with it, two samples each): the refreshes of copies 93.7 and 50.0 ms a frame of thread time against 44.0 and 28.4; the submitting thread's last refreshes 20.9 and 13.4 ms against 12.0 and 10.9; all threads' changes of protection 62.8 ms a frame against 37.5; 50 MB a frame copied against 44. Release, runs taken in turn: frames 58.5 and 61.0 ms by default, 58.8 and 67.7 with port 6, 68.2 and 57.3 with this too: no frame gain that shows, the card holds the frame where the submitting thread let go of it. Off unless asked for. The many-askers test runs with it (no write is lost between an asker's copy and the guard). Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/watch.rs | 213 ++++++++++++++++++++++++++++++-- 1 file changed, 205 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 2eab6aa..c63223d 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1709,6 +1709,12 @@ pub(crate) fn port_guard_line(frames: f64) { n[P6_RESTED_HOT], n[P6_NOT_ASKED], ); + let [named, done] = [0, 1].map(|i| LATER_DONE[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); + if named > 0.0 { + tracing::info!( + "written blocks guarded beside the askings (VICTORY_GUARD_LATER=1) per frame: {named:.1} runs named, {done:.1} blocks made read-only by the thread beside" + ); + } } /// The blocks known to be view memory (renderer port #6): guarded by us @@ -2962,12 +2968,17 @@ fn guard_shared(first: usize, last: usize, came: &[(usize, bool)], rest: std::ti let known = g.clean.word(word) & !BESIDE.word(word) | g.absent.word(word); written.extend(BitsOf(!known & in_word(word * 64, first, last)).map(|bit| word * 64 + bit)); } + // Made read-only here, or by the thread beside ([`guard_later`]): then + // the block stays as it is, written, and is told so again at the next + // asking that finds it read-only, which notes it clean. + let later = guard_later(); + let protect = |g: &Guards, from: usize, to: usize| if later { protect_later(from, to) } else { protect_claimed(g, from, to) }; let mut run: Option<(usize, usize)> = None; for &block in &written { if let Some((from, to)) = run && to != block { - protect_claimed(&g, from, to); + protect(&g, from, to); run = None; } // Told as written by this, and read by the caller after. @@ -2976,11 +2987,18 @@ fn guard_shared(first: usize, last: usize, came: &[(usize, bool)], rest: std::ti } if g.protected.contains(block) { if let Some((from, to)) = run.take() { - protect_claimed(&g, from, to); + protect(&g, from, to); } if g.clean.contains(block) { continue; } + // Another view of its page is open (the one the title wrote + // through): made read-only by the thread beside too, and the + // block noted clean by the asking after that. + if later && !covered(&g, block) { + protect_later(block, block + 1); + continue; + } // (No other claim is held here.) let mut claims = Claims::wait_for(&[block]); if g.protected.contains(block) && !g.clean.contains(block) && cover(&g, block, block + 1, Some(&mut claims)) { @@ -2989,11 +3007,11 @@ fn guard_shared(first: usize, last: usize, came: &[(usize, bool)], rest: std::ti } else if !g.foreign.contains(&block) && !g.left_alone(block) && !g.rests(block, rest) { run = Some((run.map_or(block, |r| r.0), block + 1)); } else if let Some((from, to)) = run.take() { - protect_claimed(&g, from, to); + protect(&g, from, to); } } if let Some((from, to)) = run { - protect_claimed(&g, from, to); + protect(&g, from, to); } drop(g); #[cfg(feature = "diagnostics")] @@ -3001,6 +3019,144 @@ fn guard_shared(first: usize, last: usize, came: &[(usize, bool)], rest: std::ti written } +/// With renderer port #6: whether the blocks an asking finds written are made +/// read-only by a thread beside it (`VICTORY_GUARD_LATER=1`; off unless asked +/// for), not by the asking itself. +/// +/// A refresh asks, guards what was written and copies it, on the threads the +/// submitting thread waits for. A change of protection is some 13 us under +/// Wine with its one lock for all of memory held, and every thread's wait +/// behind it: 750 a frame from the refreshes in the prologue, beside 360 from +/// the title's write faults (RTX 5060 under Proton), 30 to 45 ms a frame of +/// all threads' time in waiting for the guards' lock and in the changes +/// themselves. With the switch the asking only tells the block as written +/// and names it to the thread beside ("victory-guard"), which makes it (and +/// its pages' other views) read-only a moment later and does NOT note it +/// clean: what the title wrote between the asker's copy and the guard is in +/// no copy yet. The next asking finds the block read-only and not clean, +/// tells it as written once more, and notes it clean then, as it does for a +/// block made read-only for another view's sake. So nothing is lost; what it +/// costs is a second look at each written block, on threads that wait for no +/// one. +fn guard_later() -> bool { + #[cfg(test)] + if LATER_IN_TEST.get() { + return true; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_GUARD_LATER").is_some_and(|v| v == "1")) +} + +#[cfg(test)] +thread_local! { + /// [`guard_later`], for what this thread asks. + pub(crate) static LATER_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The runs of blocks named to the thread beside ([`guard_later`]). +static LATER: (Mutex>, std::sync::Condvar) = (Mutex::new(Vec::new()), std::sync::Condvar::new()); + +/// Since the last line: runs named to the thread beside, and the blocks it +/// made read-only. +static LATER_DONE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Names blocks `[from, to)`, found written and open by an asking, to the +/// thread that makes them read-only ([`guard_later`]). +fn protect_later(from: usize, to: usize) { + static THREAD: std::sync::Once = std::sync::Once::new(); + THREAD.call_once(|| { + let made = std::thread::Builder::new().name("victory-guard".into()).spawn(|| { + loop { + let mut runs = { + let mut named = LATER.0.lock().unwrap_or_else(|e| e.into_inner()); + while named.is_empty() { + named = LATER.1.wait(named).unwrap_or_else(|e| e.into_inner()); + } + std::mem::take(&mut *named) + }; + // Each block once, runs that touch as one. + runs.sort_unstable(); + let mut joined: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for (from, to) in runs { + match joined.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => joined.push((from, to)), + } + } + for (from, to) in joined { + // (Shared, and let go every few blocks: what takes the + // lock alone, a mapping changed or a kernel read, comes + // in, and the askings behind it.) + let mut at = from; + while at < to { + let next = (at + 4).min(to); + let g = guards_shared(); + let done = protect_named(&g, at, next); + drop(g); + LATER_DONE[1].fetch_add(done as u64, std::sync::atomic::Ordering::Relaxed); + at = next; + } + } + } + }); + if let Err(e) = made { + tracing::warn!(error = %e, "no thread to guard written blocks beside the askings (VICTORY_GUARD_LATER=1): they stay open, and are told as written at every asking"); + } + }); + LATER_DONE[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + LATER.0.lock().unwrap_or_else(|e| e.into_inner()).push((from, to)); + LATER.1.notify_one(); +} + +/// The thread beside ([`guard_later`]): makes read-only, and not clean, +/// those of blocks `[from, to)` that are still what the asking named them +/// as: view memory, open, not left alone or resting, and claimed by nobody +/// now (a block passed over is named again by the next asking that finds it +/// written). How many. +fn protect_named(g: &Guards, from: usize, to: usize) -> usize { + let rest = rest(); + let mut claims = Claims::none(); + let mut start = None; + let mut done = 0; + for block in from..to { + // (Its bit: the memory was not unmapped or freed since it was named; + // what lies there now may be no view.) + if g.protected.contains(block) { + if let Some(s) = start.take() { + protect_here_as(g, s, block, false); + cover(g, s, block, Some(&mut claims)); + } + // Read-only for another view's sake, a view of its page open: + // that one too (the asking after this notes the block clean). + if !g.clean.contains(block) && VIEWS.any(block, block + 1) && claims.try_one(block) && g.protected.contains(block) { + cover(g, block, block + 1, Some(&mut claims)); + done += 1; + } + continue; + } + let due = VIEWS.any(block, block + 1) + && !g.protected.contains(block) + && !g.absent.contains(block) + && !g.foreign.contains(&block) + && !g.left_alone(block) + && !g.rests(block, rest) + && claims.try_one(block) + && !g.protected.contains(block); + if due { + start.get_or_insert(block); + done += 1; + } else if let Some(s) = start.take() { + protect_here_as(g, s, block, false); + cover(g, s, block, Some(&mut claims)); + } + } + if let Some(s) = start { + protect_here_as(g, s, to, false); + cover(g, s, to, Some(&mut claims)); + } + done +} + /// [`protect`] of `[from, to)` with the lock shared: of the blocks whose /// claims can be had now, each run, its other views' blocks only where their /// claims can be had too. @@ -3130,6 +3286,15 @@ fn cover(g: &Guards, from: usize, to: usize, mut claims: Option<&mut Claims>) -> all } +/// Whether [`cover`] of `block` would change no protection: every other view +/// of its pages is read-only by our hand already. +fn covered(g: &Guards, block: usize) -> bool { + elsewhere(block * BLOCK, BLOCK) + .into_iter() + .filter(|(page, _)| g.protected.contains(page / BLOCK)) + .all(|(_, others)| others.into_iter().all(|other| g.protected.contains(other / BLOCK))) +} + /// Makes `block` read-only: another view of a page a copy is about to take /// through its own, so that a write through this one faults too. It is not /// noted clean: the copies of title memory at this view have not taken the @@ -3181,6 +3346,13 @@ fn protect_alias(g: &Guards, block: usize, claims: Option<&mut Claims>) -> bool /// [`protect`] for one range, without the other views of its pages. fn protect_here(g: &Guards, from: usize, to: usize) { + protect_here_as(g, from, to, true); +} + +/// [`protect_here`]; `clean`: the blocks are noted clean too (the caller +/// copies them after this; else they are told as written once more, at the +/// next asking: [`guard_later`]). +fn protect_here_as(g: &Guards, from: usize, to: usize, clean: bool) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; @@ -3211,7 +3383,9 @@ fn protect_here(g: &Guards, from: usize, to: usize) { }; let note = |g: &Guards, from: usize, to: usize| { g.protected.insert_all(from..to); - g.clean.insert_all(from..to); + if clean { + g.clean.insert_all(from..to); + } }; // Ahead of the protection (`PROTECTED`). (from..to).for_each(|block| PROTECTED.set(block)); @@ -5437,8 +5611,29 @@ mod many_askers_tests { writes_to_views_are_not_lost::<3>(0, 0); } + /// With renderer port #6 and the written blocks guarded by the thread + /// beside the askings ([`super::guard_later`]): a write between an + /// asker's copy and the guard is told at the next asking. + #[test] + fn no_write_to_views_is_lost_with_the_guard_beside() { + let done = |what: usize| super::LATER_DONE[what].load(std::sync::atomic::Ordering::Relaxed); + let before = [done(0), done(1)]; + writes_to_views_are_not_lost::<1>(0, 3); + writes_to_views_are_not_lost::<3>(0, 3); + writes_to_views_are_not_lost::<3>(50, 3); + assert!(done(0) > before[0], "no run was named to the thread beside"); + // (It guards a moment later: given that moment.) + for _ in 0..200 { + if done(1) > before[1] { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(done(1) > before[1], "the thread beside made no block read-only"); + } + /// `port`: 0, renderer port #6 off; 1, on in all threads; 2, on in every - /// other thread. + /// other thread; 3, on in all threads with the guard beside the askings. fn writes_to_views_are_not_lost(rest: u64, port: u8) { let rest = std::time::Duration::from_micros(rest); const PAGES: usize = 12; @@ -5472,7 +5667,8 @@ mod many_askers_tests { if VIEWS > 1 { s.spawn(move || { super::REST_IN_TEST.set(rest); - super::PORT_GUARD_IN_TEST.set(port == 1); + super::PORT_GUARD_IN_TEST.set(port == 1 || port == 3); + super::LATER_IN_TEST.set(port == 3); let mut last = [0u64; VIEWS]; for round in 0..300usize { let (page, asked) = (round * 5 % PAGES, round % VIEWS); @@ -5503,7 +5699,8 @@ mod many_askers_tests { let (by_bits, past, title_beside) = (&by_bits, &past, &title_beside); s.spawn(move || { super::REST_IN_TEST.set(rest); - super::PORT_GUARD_IN_TEST.set(port == 1 || port == 2 && t % 2 == 1); + super::PORT_GUARD_IN_TEST.set(port == 1 || port == 3 || port == 2 && t % 2 == 1); + super::LATER_IN_TEST.set(port == 3); super::HOT_IN_TEST.set(if rest.is_zero() { 0 } else { 20 }); let mut last = [[0u64; PAGES]; VIEWS]; let mut seed = t as u64 * 7919 + 1;