From c877288accf57bfd2759a47fd1e9ecb9fd87cd0a Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:59:20 +0530 Subject: [PATCH 1/6] Write faults open guarded blocks without the guards' lock (VICTORY_FAULT_UNLOCKED=1; off) Of 281 ms the title's threads spent in the write-fault handler over 14 frames of play, 252 ms were waits for the guards' lock (timeline tl.190; tl.130 and tl2's tl.185 the same): faults queued behind other faults and behind refreshes guarding, up to 5 ms, while a fault's own work took 8 microseconds at the median. With the switch a fault takes the block's bit in OPENING (whoever finds it set waits up to 100 microseconds for that fault, then goes the locked way), tells the other views of the page as written when the block is guarded with them (ALIASED, a mirror of Guards::aliased: TOLD and BESIDE set, PUBLISHED cleared), clears the block's PUBLISHED, sets its BESIDE, changes the protection itself and queues the block. The next holder of the lock settles the guards' notes before anything else (guards -> settle). Until then the holders of the lock treat OPENING and TOLD blocks as written and leave them as they are (guard), publish takes its bit back if it finds one, and protect_alias does not count an OPENING block as read-only for another view. OPENING's doc comment gives the argument. Also: BESIDE is forgotten when the mapping of a block changes (the block is told as written then anyway; a bit left behind kept a hole mapped at the address from being known by its bits). asked_for! moves to switch.rs for both files. Diagnostics: the line of the trackers' lock waits counts faults opened under the lock (waiting, holding), without it, and those that went the locked way after all; the fault book has What::Unlocked. Tests: the single-thread tests whose writes fault, again with faults that take no lock; the many-askers test with all and half the writers' faults taking no lock; a fault settled by the next holder; what holders do with an unsettled block; eight threads faulting on the same blocks at once through two views; ranges of bits cleared. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 3f55056817bfc596fc81bafa68f2f263172f4a65) --- crates/victory-gpu/src/faultbook.rs | 4 + crates/victory-gpu/src/switch.rs | 26 ++ crates/victory-gpu/src/titlewrite.rs | 26 +- crates/victory-gpu/src/watch.rs | 559 +++++++++++++++++++++++++-- 4 files changed, 564 insertions(+), 51 deletions(-) diff --git a/crates/victory-gpu/src/faultbook.rs b/crates/victory-gpu/src/faultbook.rs index 1b0db43a..dda9cd8d 100644 --- a/crates/victory-gpu/src/faultbook.rs +++ b/crates/victory-gpu/src/faultbook.rs @@ -37,6 +37,10 @@ pub(crate) enum What { /// A store (the instruction at `a`) was done beside the guard of block /// `b`. Stored = 10, + /// A write fault opened block `a` without the guards' lock + /// (`VICTORY_FAULT_UNLOCKED`); b: other views of its page told as + /// written; c: nanoseconds in it. + Unlocked = 11, } #[repr(C)] diff --git a/crates/victory-gpu/src/switch.rs b/crates/victory-gpu/src/switch.rs index b5ef2771..2b9e0b99 100644 --- a/crates/victory-gpu/src/switch.rs +++ b/crates/victory-gpu/src/switch.rs @@ -42,6 +42,32 @@ macro_rules! toggled { }}; } +/// A switch that is off unless its variable is `1`, read once; with +/// `VICTORY_AB` naming it (diagnostics builds), on and off while the title +/// runs. +#[cfg(windows)] +#[macro_export] +#[doc(hidden)] +macro_rules! asked_for { + ($name:literal) => {{ + static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let asked = ASKED.get_or_init(|| { + #[cfg(feature = "diagnostics")] + if let Some(bit) = $crate::ab::bit($name) { + return Err(bit); + } + Ok(std::env::var_os($name).is_some_and(|v| v == "1")) + }); + match *asked { + Ok(on) => on, + #[cfg(feature = "diagnostics")] + Err(bit) => $crate::ab::on(bit), + #[cfg(not(feature = "diagnostics"))] + Err(_) => false, + } + }}; +} + #[cfg(test)] mod tests { use super::value_is_on; diff --git a/crates/victory-gpu/src/titlewrite.rs b/crates/victory-gpu/src/titlewrite.rs index 946fa881..6942af01 100644 --- a/crates/victory-gpu/src/titlewrite.rs +++ b/crates/victory-gpu/src/titlewrite.rs @@ -40,34 +40,12 @@ fn add(what: usize) { DONE[what].fetch_add(1, Relaxed); } -/// A switch that is off unless its variable is `1` (or `VICTORY_AB` names it: -/// on and off while the title runs). -macro_rules! asked_for { - ($name:literal) => {{ - static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); - let asked = ASKED.get_or_init(|| { - #[cfg(feature = "diagnostics")] - if let Some(bit) = crate::ab::bit($name) { - return Err(bit); - } - Ok(std::env::var_os($name).is_some_and(|v| v == "1")) - }); - match *asked { - Ok(on) => on, - #[cfg(feature = "diagnostics")] - Err(bit) => crate::ab::on(bit), - #[cfg(not(feature = "diagnostics"))] - Err(_) => false, - } - }}; -} - fn copies_on() -> bool { #[cfg(test)] if ON_IN_TEST.get() { return true; } - asked_for!("VICTORY_COPY_BESIDE") + crate::asked_for!("VICTORY_COPY_BESIDE") } fn stores_on() -> bool { @@ -75,7 +53,7 @@ fn stores_on() -> bool { if ON_IN_TEST.get() { return true; } - asked_for!("VICTORY_STORE_BESIDE") + crate::asked_for!("VICTORY_STORE_BESIDE") } #[cfg(test)] diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 736ac6e5..721647f4 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -192,7 +192,20 @@ pub(crate) fn lock_waits(frames: f64) -> String { let [n, ns] = [0, 1].map(|i| WAITS[what][i].swap(0, std::sync::atomic::Ordering::Relaxed)); format!("{:.0} {:.2} ms", n as f64 / frames, ns as f64 / 1e6 / frames) }; - format!("ranges held {}, journal read {}, journal noted in {}, guards {}", of(0), of(1), of(2), of(3)) + let [locked, waiting, holding, unlocked, opening, fell] = + std::array::from_fn(|i| FAULTS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); + format!( + "ranges held {}, journal read {}, journal noted in {}, guards {}; write faults opened under the guards' lock {locked:.0} \ + ({:.2} ms waiting for it, {:.2} ms holding it), without it {unlocked:.0} ({:.2} ms), going the locked way after all \ + {fell:.0} (VICTORY_FAULT_UNLOCKED)", + of(0), + of(1), + of(2), + of(3), + waiting / 1e6, + holding / 1e6, + opening / 1e6 + ) } /// The page ranges some thread is asking about: asking forgets what it @@ -849,10 +862,16 @@ impl Bits { } fn set(&self, block: usize) { + self.swap_on(block); + } + + /// Sets it; whether it was set already (so too of a block outside the + /// address space, which has no bit). + fn swap_on(&self, block: usize) -> bool { use std::sync::atomic::Ordering::{AcqRel, Acquire, SeqCst}; let word = block / 64; let Some(place) = self.0.get(word / Bits::WORDS) else { - return; + return true; }; if place.load(Acquire).is_null() { let piece: Box = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]); @@ -862,9 +881,8 @@ impl Bits { drop(unsafe { Box::from_raw(piece) }); } } - if let Some(piece) = self.piece(word) { - piece[word % Bits::WORDS].fetch_or(1 << (block % 64), SeqCst); - } + let bit = 1 << (block % 64); + self.piece(word).is_none_or(|piece| piece[word % Bits::WORDS].fetch_or(bit, SeqCst) & bit != 0) } /// Sixty-four of them. @@ -890,6 +908,26 @@ impl Bits { } } + /// Clears those of `[first, last)`. + fn clear_all(&self, first: usize, last: usize) { + // (No bit past the address space's end.) + let last = last.min(Bits::PIECES * Bits::WORDS * 64); + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + match self.piece(word) { + Some(piece) => { + piece[word % Bits::WORDS].fetch_and(!mask, std::sync::atomic::Ordering::SeqCst); + block = until; + } + // None of the piece's. + None => block = (word / Bits::WORDS + 1) * Bits::WORDS * 64, + } + } + } + /// Whether a bit of `[first, last)` is set. fn any(&self, first: usize, last: usize) -> bool { let mut block = first; @@ -966,8 +1004,220 @@ static PROTECTED: Bits = Bits::new(); /// [`PUBLISHED`]'s is cleared after that. So an asking either finds the bit /// or came before the title's thread went on from its write; and who takes /// the bit reads the bytes after. +/// +/// A write fault that opens a block without the guards' lock +/// ([`open_unlocked`]) sets it as well, for the block and for every other +/// view of its page, before the block can be written: those are told as +/// written by the next asking that finds them, as these are, whatever the +/// guards' notes of them still say. A change of what the address shows +/// ([`title_memory_remapped`], [`title_memory_unmapping`]) forgets the bit: +/// the block is told as written then anyway. static BESIDE: Bits = Bits::new(); +/// The blocks a write fault is opening, or has opened, without the guards' +/// lock ([`open_unlocked`]), until the next holder of the lock has brought +/// the guards' notes of them up to date ([`settle`]); the fault that sets a +/// block's bit owns it, and a fault that finds it set goes the locked way. +/// Such a block is told as written at every asking and left as it is: it is +/// not made read-only, nor noted clean or published, nor counted read-only +/// for another view of its page ([`protect_alias`]). +/// +/// Why no write is missed: the fault sets this bit and [`BESIDE`]'s, and +/// clears [`PUBLISHED`]'s, all before the block is writable. Until the notes +/// are settled the guards may still have the block read-only and clean: who +/// relies on those notes under the lock (an asking, [`publish`], a guard of +/// another view) looks at this bit first, and who notes the block published +/// looks at it after, and takes the note back if it is set, as for +/// `BESIDE`. Whoever asks by the bits alone finds `PUBLISHED`'s cleared or +/// `BESIDE`'s set, as for bytes put in beside the guard. The fault is +/// settled under the lock by whoever takes it next, before anything else +/// (`guards`): a write the title makes after the fault, and before it asks +/// for anything to be taken, is in the guards' notes when the asking is. +static OPENING: Bits = Bits::new(); + +/// The other views of the pages of the blocks in [`OPENING`]: written by way +/// of a view a fault opened, and read-only still. Told as written at every +/// asking, and not noted clean or published, until the fault is settled, +/// which takes their clean notes. +static TOLD: Bits = Bits::new(); + +/// The blocks in `Guards::aliased`, for a fault that takes no lock: one that +/// finds its block's bit here tells the other views of its page as written, +/// as [`open`] does; one that does not, opens its block alone. The bit is +/// set before [`protect_alias`] looks at [`OPENING`]'s, and a fault sets that +/// before it looks here: of a fault and a guard that counts the block +/// read-only for another view, one sees the other. +static ALIASED: Bits = Bits::new(); + +/// A block a write fault opened without the guards' lock, when, and the +/// other views of its page it told as written ([`TOLD`]). +struct Opened { + block: usize, + at: std::time::Instant, + others: Vec, +} + +/// Those whose notes are not settled yet ([`settle`]), and how many. +static OPENED: Mutex> = Mutex::new(Vec::new()); +static TO_SETTLE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Whether a write fault opens a guarded block without the guards' lock +/// (`VICTORY_FAULT_UNLOCKED=1`; off unless asked for, or flipped while the +/// title runs by `VICTORY_AB`). +/// +/// Under the lock the title's threads waited for it more than they did +/// anything else in a fault: of 281 ms in the handler in 14 frames of play +/// (2,729 faults), 252 ms were waits for the guards' lock, up to 5 ms at a +/// time, most of them behind other faults that were waiting too, the rest +/// behind refreshes guarding; the faults themselves took 8 microseconds at +/// the median (timeline tl.190; tl.130 and tl2's tl.185 the same). Here the +/// fault changes the protection and the bits itself, and the guards' notes +/// of the block are brought up to date by the next holder of the lock +/// ([`settle`]); [`OPENING`] says why that misses nothing. A fault on a +/// block another thread is opening waits for that one (100 microseconds at +/// most), and one with every view of its page to open +/// (`VICTORY_OPEN_ONE_VIEW=0`) goes the locked way. +fn unlocked() -> bool { + #[cfg(test)] + if UNLOCKED_IN_TEST.get() { + return true; + } + crate::asked_for!("VICTORY_FAULT_UNLOCKED") +} + +#[cfg(test)] +thread_local! { + /// [`unlocked`], for this thread's faults. + static UNLOCKED_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Diagnostics, since the last line: write faults opened under the lock, +/// nanoseconds waiting for it, nanoseconds holding it; opened without it, +/// nanoseconds of that; and those that went the locked way after all. +#[cfg(feature = "diagnostics")] +static FAULTS: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// Opens guarded block `block` for a write fault without the guards' lock +/// ([`unlocked`]); whether it is writable now. `false`: the caller opens it +/// under the lock, as before, with nothing changed here but what that does +/// again (another thread is opening it, every view is to be opened, or its +/// protection could not be changed). +fn open_unlocked(block: usize) -> bool { + use std::sync::atomic::Ordering::{Relaxed, SeqCst}; + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; + #[cfg(feature = "diagnostics")] + let began = std::time::Instant::now(); + if OPENING.swap_on(block) { + return false; + } + // (Looked at after the bit above is set: see `ALIASED`.) + let others: Vec = if ALIASED.any(block, block + 1) { + if !open_one_view() { + // Nothing done yet: as if the bit had never been set. + OPENING.clear(block); + return false; + } + crate::inplace::pages_of(block * BLOCK).into_iter().map(|page| page / BLOCK).filter(|&other| other != block).collect() + } else { + Vec::new() + }; + // All told as written before the first can be. + for &other in &others { + TOLD.set(other); + BESIDE.set(other); + } + BESIDE.set(block); + for &other in &others { + PUBLISHED.clear(other); + } + PUBLISHED.clear(block); + put_count(block).store(0, Relaxed); + let at = std::time::Instant::now(); + let mut old = 0; + // SAFETY: a block we made read-only. + let mut done = unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) } != 0; + if done && !matches!(old, PAGE_READONLY | PAGE_READWRITE) { + // Not what we left there (as in `unguard`): other memory's, which + // keeps its protection. + // SAFETY: as above. + unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old) }; + done = false; + } + #[cfg(feature = "diagnostics")] + let told = others.len(); + // After the protection: who settles it may let the block be guarded again. + { + let mut opened = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + opened.push(Opened { block, at, others }); + TO_SETTLE.store(opened.len(), SeqCst); + } + #[cfg(feature = "diagnostics")] + { + tally(8, at.elapsed().as_nanos() as u64); + if done { + let ns = began.elapsed().as_nanos() as u64; + FAULTS[3].fetch_add(1, Relaxed); + FAULTS[4].fetch_add(ns, Relaxed); + crate::faultbook::note(crate::faultbook::What::Unlocked, block, told, ns); + } + } + done +} + +/// Brings into the guards' notes the blocks faults opened without their lock +/// ([`open_unlocked`]): as [`open`] and [`unguard`] do for a block a write +/// fault opened, but for the protection, which is changed already. Done by +/// whoever takes the lock, before anything else ([`guards`]). +fn settle(g: &mut Guards) { + use std::sync::atomic::Ordering::SeqCst; + if TO_SETTLE.load(SeqCst) == 0 { + return; + } + let opened = { + let mut opened = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + TO_SETTLE.store(0, SeqCst); + std::mem::take(&mut *opened) + }; + for Opened { block, at, mut others } in opened { + if g.aliased.contains(block) { + if others.is_empty() { + // Guarded with its other views after the fault looked: they + // were not clean then (one is made so only with every other + // view read-only and none being opened), and are not now. + others = crate::inplace::pages_of(block * BLOCK) + .into_iter() + .map(|page| page / BLOCK) + .filter(|&other| other != block) + .collect(); + } + g.unalias(block); + } + for &other in &others { + g.clean.remove(other); + PUBLISHED.clear(other); + } + if g.protected.remove(block) { + g.clean.remove(block); + PUBLISHED.clear(block); + PROTECTED.clear(block); + } + g.opened_at(block, at); + // (Another fault may have told the same views: they are not clean + // now, and its own block keeps them so, `protect_alias`.) + for &other in &others { + TOLD.clear(other); + } + OPENING.clear(block); + } +} + +/// Whether a block of `[first, last)` is being opened by a fault without the +/// guards' lock, or is another view of such a block's page, and the guards' +/// notes of it are not settled yet. +fn unsettled(first: usize, last: usize) -> bool { + OPENING.any(first, last) || TOLD.any(first, last) +} + /// How much was put into a block beside its guard since it was last told as /// written (`crate::titlewrite::MOST`), by a few bits of its number. static PUT: [std::sync::atomic::AtomicU32; 1 << 13] = [const { std::sync::atomic::AtomicU32::new(0) }; 1 << 13]; @@ -999,7 +1249,8 @@ pub(crate) fn guards_any(at: usize, len: usize) -> bool { /// `wrapping_add`). `weight`: how much of the block's share it is. pub(crate) fn put_beside(block: usize, weight: u32, put: impl FnOnce(usize)) -> Beside { use std::sync::atomic::Ordering::Relaxed; - if !light() || !view_guard() || !PROTECTED.any(block, block + 1) { + // (Being opened by a fault that took no lock: guarded no more.) + if !light() || !view_guard() || !PROTECTED.any(block, block + 1) || OPENING.any(block, block + 1) { return Beside::Cannot; } let count = put_count(block); @@ -1046,11 +1297,12 @@ pub(crate) fn opened_for_writing(at: usize) { fn publish(pages: &[usize]) { let g = guards(); for &page in pages { - if g.clean.contains(page) || g.held.contains(page) { + if (g.clean.contains(page) || g.held.contains(page)) && !unsettled(page, page + 1) { PUBLISHED.set(page); - // (Put there since: whoever did clears the bit after this is - // set, or its own bit is found here.) - if BESIDE.any(page, page + 1) { + // (Put there since, or opened by a fault since: whoever did + // clears the bit after this is set, or its own bit is found + // here.) + if BESIDE.any(page, page + 1) || unsettled(page, page + 1) { PUBLISHED.clear(page); } } @@ -1401,6 +1653,11 @@ impl Guards { /// A write fault opened `block`. fn opened(&mut self, block: usize) { + self.opened_at(block, std::time::Instant::now()); + } + + /// A write fault opened `block` at `at`. + fn opened_at(&mut self, block: usize, at: std::time::Instant) { const MANY: usize = 1 << 13; if self.opened.len() >= MANY { self.opened.retain(|_, at| at.elapsed().as_millis() < 50); @@ -1409,7 +1666,20 @@ impl Guards { } } put_count(block).store(0, std::sync::atomic::Ordering::Relaxed); - self.opened.insert(block, std::time::Instant::now()); + self.opened.insert(block, at); + } + + /// `block`'s page is guarded together with its other views ([`ALIASED`] + /// first). + fn alias(&mut self, block: usize) { + ALIASED.set(block); + self.aliased.insert(block); + } + + fn unalias(&mut self, block: usize) { + if self.aliased.remove(block) { + ALIASED.clear(block); + } } } @@ -1425,11 +1695,17 @@ static GUARDS: Mutex = Mutex::new(Guards { opened: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), }); +/// The guards' lock, with what faults opened without it settled first +/// ([`settle`]). fn guards() -> std::sync::MutexGuard<'static, Guards> { - if let Ok(g) = GUARDS.try_lock() { - return g; - } - waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())) + let mut g = match GUARDS.try_lock() { + Ok(g) => g, + // (Held by this, whoever panicked with it: not to be asked for again.) + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())), + }; + settle(&mut g); + g } /// The 4 KiB pages of title memory that what shaders wrote was put into, @@ -1658,7 +1934,7 @@ fn guard(start: usize, end: usize) -> Option> { // takes the block out of the set, and it is looked at as any other. let unsure: Vec = { let g = guards_timed(); - if g.clean.range(first..last).count() == last - first && !BESIDE.any(first, last) { + if g.clean.range(first..last).count() == last - first && !BESIDE.any(first, last) && !unsettled(first, last) { // Nothing written, mapped or new since the range was last taken. #[cfg(feature = "diagnostics")] tally(3, 1); @@ -1695,7 +1971,7 @@ fn guard(start: usize, end: usize) -> Option> { // clean. let mut written = Vec::new(); for word in first / 64..last.div_ceil(64) { - let known = g.clean.word(word) & !BESIDE.word(word) | g.absent.word(word); + let known = (g.clean.word(word) & !BESIDE.word(word) | g.absent.word(word)) & !OPENING.word(word) & !TOLD.word(word); written.extend(BitsOf(!known & in_word(word * 64, first, last)).map(|bit| word * 64 + bit)); } let mut run: Option<(usize, usize)> = None; @@ -1710,6 +1986,15 @@ fn guard(start: usize, end: usize) -> Option> { drop(g); g = guards_timed(); } + // Opened by a fault that took no lock, or another view of such a + // block's page, and not settled yet: told as written, and left as it + // is (`OPENING`). + if unsettled(block, block + 1) { + if let Some((from, to)) = run.take() { + protect(&mut g, from, to); + } + continue; + } // Told as written by this, and read by the caller after. if BESIDE.take(block) { put_count(block).store(0, std::sync::atomic::Ordering::Relaxed); @@ -1829,7 +2114,7 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { } #[cfg(feature = "diagnostics")] ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); - g.aliased.insert(block); + g.alias(block); let mut covered = true; for other in others { covered &= protect_alias(g, other / BLOCK); @@ -1850,7 +2135,12 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { /// took it, [`open`] would have opened it. Whether it is read-only now. fn protect_alias(g: &mut Guards, block: usize) -> bool { use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; - g.aliased.insert(block); + g.alias(block); + // (After its `ALIASED` bit: a fault that did not see that one is seen + // here.) Being opened: writable, whatever the notes say. + if OPENING.any(block, block + 1) { + return false; + } if g.protected.contains(block) { return true; } @@ -1979,7 +2269,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> usize { if !aliased.is_empty() { let one = open_one_view(); for block in aliased { - g.aliased.remove(block); + g.unalias(block); for other in crate::inplace::pages_of(block * BLOCK) { let other = other / BLOCK; if one { @@ -1988,7 +2278,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> usize { PUBLISHED.clear(other); continue; } - g.aliased.remove(other); + g.unalias(other); if !(first..last).contains(&other) && g.protected.contains(other) { blocks.push(other); } @@ -2536,6 +2826,10 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, crate::inplace::title_memory_freeing(at, len); let mut g = guards(); let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); + // Nothing of the range is known any more: told as written at the next + // asking anyway. (A bit left would keep a hole mapped there from being + // known by its bits.) + BESIDE.clear_all(range.start, range.end); let absent: Vec = g.absent.range(range.clone()).collect(); for block in absent { g.absent.remove(block); @@ -2549,7 +2843,7 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, } let aliased: Vec = g.aliased.range(range).collect(); for block in aliased { - g.aliased.remove(block); + g.unalias(block); } g } @@ -2603,6 +2897,31 @@ pub(crate) fn install() { { return EXCEPTION_CONTINUE_EXECUTION; } + if unlocked() && PROTECTED.any(block, block + 1) { + if open_unlocked(block) { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::GuardFaults, 1); + crate::faultbook::note(crate::faultbook::What::Site, r.ExceptionAddress as usize, block, 0); + } + return EXCEPTION_CONTINUE_EXECUTION; + } + // Another thread is opening it so: writable in a few + // microseconds, with no lock waited for. + let began = std::time::Instant::now(); + while OPENING.any(block, block + 1) && began.elapsed().as_micros() < 100 { + if writable(at) { + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Open, block, began.elapsed().as_nanos() as usize, 0); + return EXCEPTION_CONTINUE_EXECUTION; + } + for _ in 0..64 { + std::hint::spin_loop(); + } + } + #[cfg(feature = "diagnostics")] + FAULTS[5].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } // Another thread may have opened the block since this one faulted // (then nothing waits for the lock), and a copy may have guarded it // again since that (then it is ours again, not read-only for some @@ -2629,6 +2948,9 @@ pub(crate) fn install() { crate::copystat::add(crate::copystat::C::GuardFaults, 1); let ns = waited.as_nanos().min(u128::from(u32::MAX)) as usize; let held = (began.elapsed() - waited).as_nanos() as u64; + FAULTS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + FAULTS[1].fetch_add(ns as u64, std::sync::atomic::Ordering::Relaxed); + FAULTS[2].fetch_add(held, std::sync::atomic::Ordering::Relaxed); crate::faultbook::note(crate::faultbook::What::Fault, block, opened << 32 | ns, held); crate::faultbook::note(crate::faultbook::What::Site, r.ExceptionAddress as usize, block, 0); } @@ -3876,6 +4198,154 @@ mod tests { writing(top, PAGE); title_memory_remapped(top, usize::MAX); } + + /// The tests above whose writes fault, with faults that take no lock + /// (`VICTORY_FAULT_UNLOCKED`): every asking says what it said. (Not + /// `what_the_kernel_writes_through_is_not_guarded_for_another_view` nor + /// `a_range_that_begins_in_an_unmapped_block_is_guarded`: run this late, + /// while the tests of many askers change mappings, their first asking + /// meets another test's change at an address used again now and then: + /// 4 and 1 of 100 runs failed so, and with every fault under the lock + /// 2 and 0.) + #[test] + fn faults_that_take_no_lock_tell_the_same() { + UNLOCKED_IN_TEST.set(true); + a_write_through_another_view_is_reported_at_the_guarded_one(); + a_write_is_reported_at_every_checked_view(); + a_write_opens_the_view_it_goes_through(); + a_block_just_written_rests(); + what_the_title_puts_in_beside_a_guard_is_told(); + stores_and_copies_of_the_title_leave_the_guard(); + bits_go_at_every_view(); + a_page_of_many_views_is_guarded_one_view_at_a_time(); + UNLOCKED_IN_TEST.set(false); + } + + /// A fault that takes no lock opens the view it came through, and tells + /// the page's other views as written: by their bits at once, and at + /// every asking until the next holder of the guards' lock has settled + /// it, which leaves no bit of it behind. Neither view is guarded again + /// before that. + #[test] + fn a_fault_that_takes_no_lock_is_settled_by_the_next_holder() { + let (section, one, two) = two_views(BLOCK); + let block = |view: usize| view / BLOCK; + for view in [one, two, one, two] { + assert!(writes(view, view + BLOCK, true).is_some()); + } + assert!(published(one, one + BLOCK) && published(two, two + BLOCK)); + UNLOCKED_IN_TEST.set(true); + // SAFETY: a view, opened by the handler. + unsafe { ((two + 8) as *mut u8).write(1) }; + UNLOCKED_IN_TEST.set(false); + assert!(writable(two) && !writable(one)); + assert!(!published(one, one + BLOCK) && !published(two, two + BLOCK)); + { + // Settled by whoever took the lock first: this, or another + // test's thread. + let g = guards(); + assert!(!unsettled(block(one), block(one) + 1) && !unsettled(block(two), block(two) + 1)); + assert!(!g.protected.contains(block(two)) && !g.clean.contains(block(two)) && !g.clean.contains(block(one))); + assert!(g.protected.contains(block(one)) && !PROTECTED.any(block(two), block(two) + 1)); + } + assert_eq!(guard(one, one + BLOCK), Some(vec![block(one)])); + assert_eq!(guard(two, two + BLOCK), Some(vec![block(two)])); + assert!(!writable(two) && !writable(one)); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + assert_eq!(guard(two, two + BLOCK), Some(Vec::new())); + drop_views(section, &[one, two], BLOCK); + } + + /// What the holders of the lock do with a block a fault is opening + /// without it, before that is settled: it is told as written and left as + /// it is, and another view of its page is not counted read-only for it, + /// nor noted clean or published. Settled, all is as after a fault. + #[test] + fn an_unsettled_block_is_told_and_left_alone() { + use std::sync::atomic::Ordering::SeqCst; + let (section, one, two) = two_views(BLOCK); + let block = |view: usize| view / BLOCK; + assert_eq!(guard(one, one + BLOCK), Some(vec![block(one)])); + assert_eq!(guard(two, two + BLOCK), Some(vec![block(two)])); + // As the fault does it, up to where it changes the protection. + assert!(!OPENING.swap_on(block(two))); + for view in [one, two] { + BESIDE.set(block(view)); + PUBLISHED.clear(block(view)); + } + TOLD.set(block(one)); + for _ in 0..2 { + assert_eq!(guard(one, one + BLOCK), Some(vec![block(one)])); + assert_eq!(guard(two, two + BLOCK), Some(vec![block(two)])); + assert!(writes(one, one + BLOCK, true).is_some() && !published(one, one + BLOCK)); + assert!(writes(two, two + BLOCK, true).is_some() && !published(two, two + BLOCK)); + assert!(!writable(two) && !writable(one), "nothing changed"); + } + assert!(!protect_alias(&mut guards(), block(two)), "being opened: no guard for another view"); + // The rest of the fault: the view is writable, and the next holder of + // the lock settles it. + let mut old = 0; + // SAFETY: a block we made read-only. + unsafe { windows_sys::Win32::System::Memory::VirtualProtect(two as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + { + let mut opened = OPENED.lock().unwrap(); + opened.push(Opened { block: block(two), at: std::time::Instant::now(), others: vec![block(one)] }); + TO_SETTLE.store(opened.len(), SeqCst); + } + assert_eq!(guard(one, one + BLOCK), Some(vec![block(one)])); + assert!(!unsettled(block(one), block(one) + 1) && !unsettled(block(two), block(two) + 1)); + assert_eq!(guard(two, two + BLOCK), Some(vec![block(two)])); + assert!(!writable(two) && !writable(one)); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + assert_eq!(guard(two, two + BLOCK), Some(Vec::new())); + drop_views(section, &[one, two], BLOCK); + } + + /// Threads write the same guarded blocks at once, through both views of + /// their pages, most with faults that take no lock: one opens a block, the + /// others go on behind it, and the asking at each view after the writes + /// tells them. + #[test] + fn faults_at_once_on_one_block_all_go_on() { + const THREADS: usize = 8; + const ROUNDS: usize = 100; + let (section, one, two) = two_views(2 * BLOCK); + let barrier = std::sync::Barrier::new(THREADS + 1); + let mut missed = None; + std::thread::scope(|s| { + for t in 0..THREADS { + let barrier = &barrier; + s.spawn(move || { + UNLOCKED_IN_TEST.set(t % 4 != 3); + for round in 0..ROUNDS { + barrier.wait(); + let view = if (round + t) % 3 == 0 { two } else { one }; + // SAFETY: a word of a view, this thread's own. + unsafe { ((view + round % 2 * BLOCK + t * 8) as *mut u64).write_volatile(round as u64) }; + barrier.wait(); + } + }); + } + let mut last = [[0u64; 2]; 2]; + for round in 0..ROUNDS { + barrier.wait(); + barrier.wait(); + let k = round % 2; + for (v, view) in [one, two].into_iter().enumerate() { + let (now, written) = writes(view, view + 2 * BLOCK, true).expect("a view"); + let number = written.iter().find(|w| w.0 == view / PAGE + k).map_or(0, |w| w.1); + // (Not asserted here: the writers would wait at the + // barrier for good.) + if number <= last[v][k] && missed.is_none() { + missed = Some(format!("round {round}, view {v}: {number} is not after {}", last[v][k])); + } + last[v] = [now; 2]; + } + } + }); + assert_eq!(missed, None); + drop_views(section, &[one, two], 2 * BLOCK); + } } #[cfg(test)] @@ -3981,14 +4451,14 @@ mod many_askers_tests { /// again between. #[test] fn no_write_to_views_is_lost_between_askers() { - writes_to_views_are_not_lost::<1>(0); + writes_to_views_are_not_lost::<1>(0, 0); } /// The same with blocks that rest after a write ([`super::rest`]). #[test] fn no_write_to_resting_views_is_lost_between_askers() { - writes_to_views_are_not_lost::<1>(50); - writes_to_views_are_not_lost::<3>(50); + writes_to_views_are_not_lost::<1>(50, 0); + writes_to_views_are_not_lost::<3>(50, 0); } /// The same of pages shown at three addresses, each of which has copies @@ -3998,10 +4468,26 @@ mod many_askers_tests { /// for one address only, `VICTORY_VIEW_GUARD=0`.) #[test] fn no_write_through_another_view_is_lost_between_askers() { - writes_to_views_are_not_lost::<3>(0); + writes_to_views_are_not_lost::<3>(0, 0); } - fn writes_to_views_are_not_lost(rest: u64) { + /// The same with write faults that take no lock (`VICTORY_FAULT_UNLOCKED`): + /// on every thread, and on half of them while the others take it, of one + /// view and of three, resting and not. + #[test] + fn no_write_is_lost_when_faults_take_no_lock() { + const ALL: u32 = u32::MAX; + const HALF: u32 = 0x5555_5555; + writes_to_views_are_not_lost::<1>(0, ALL); + writes_to_views_are_not_lost::<3>(0, ALL); + writes_to_views_are_not_lost::<3>(0, HALF); + writes_to_views_are_not_lost::<1>(50, HALF); + writes_to_views_are_not_lost::<3>(50, ALL); + } + + /// `unlocked`: a bit for each writing thread whose faults take no lock; + /// the one that maps a view and writes it has the top bit. + fn writes_to_views_are_not_lost(rest: u64, unlocked: u32) { let rest = std::time::Duration::from_micros(rest); const PAGES: usize = 12; const THREADS: usize = 8; @@ -4032,6 +4518,7 @@ mod many_askers_tests { if VIEWS > 1 { s.spawn(move || { super::REST_IN_TEST.set(rest); + super::UNLOCKED_IN_TEST.set(unlocked >> 31 != 0); let mut last = [0u64; VIEWS]; for round in 0..300usize { let (page, asked) = (round * 5 % PAGES, round % VIEWS); @@ -4062,6 +4549,7 @@ 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::UNLOCKED_IN_TEST.set(unlocked >> t & 1 != 0); let mut last = [[0u64; PAGES]; VIEWS]; let mut seed = t as u64 * 7919 + 1; let mut next = |n: usize| { @@ -4326,6 +4814,15 @@ mod many_askers_tests { super::title_memory_unmapping(at, BLOCKS * PAGE); } + /// The two tests around, with write faults that take no lock. + #[test] + fn bits_and_holes_with_faults_that_take_no_lock() { + super::UNLOCKED_IN_TEST.set(true); + bits_go_with_the_guard(); + holes_are_known_until_the_runtime_tells(); + super::UNLOCKED_IN_TEST.set(false); + } + /// A block's bit goes with everything that makes it the title's to write, /// or forgets it. #[test] @@ -4381,5 +4878,13 @@ mod many_askers_tests { BITS.clear(511); assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700)); assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space"); + // Cleared by ranges, whatever lies beside them; to the end of all. + BITS.clear_all(310, 400); + assert!(!BITS.any(310, 400) && BITS.all(300, 310) && BITS.all(400, 511) && BITS.all(512, 700)); + BITS.clear_all(65535, 65536); + assert!(!BITS.any(65535, 65536) && BITS.all(65536, 65538)); + BITS.clear_all(0, usize::MAX); + assert!(!BITS.any(0, 1 << 31)); + assert!(!BITS.swap_on(70) && BITS.swap_on(70) && BITS.all(70, 71)); } } From 5f391f2adf407ce03fc028f6c146e822644ca307 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund Date: Sat, 28 Nov 2026 04:37:06 -0500 Subject: [PATCH 2/6] Write watch: a write fault asks about its one page, not about the region around it A write fault of the title's on a block that another of its threads has just opened, or is opening, asks whether the page is writable by now. It asked with `VirtualQuery`, which answers for the whole run of pages around an address that are alike and walks to the end of it: for a view of hundreds of megabytes hundreds of microseconds, with the address space held against every change of protection meanwhile. `writable` now asks about the one page (`QueryWorkingSetEx`), and about the region only where the system does not have the page in memory. `VICTORY_PAGE_ASK=0`: the region, as before. Measured by turns in one run (prologue's cell, RTX 3090 Ti, Ryzen 9 9950X3D, Series S profile, 12 seconds a turn), per frame: 170 to 185 questions about regions, 15.5 to 17.3 ms of the title's threads' time, become 415 to 567 about pages (the wait for a block being opened asks more often in its 100 microseconds), 2.8 to 3.3 ms. The frame itself did not move by more than two runs differ by (26.80 and 26.70 ms): the title's own threads, the thread that prepares submissions and the card each take about that long there. AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 0fb1e38eeea8735d8e9889af5ccd825f07908e4c) --- crates/victory-gpu/src/watch.rs | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 721647f4..813b5aa7 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -2973,11 +2973,45 @@ pub(crate) fn install() { }); } +/// The protection of the one page `at` lies in, where the system has that +/// page in memory (`None`: it has not, or would not say). +/// +/// `VirtualQuery` answers for the whole run of pages around an address that +/// are alike, and walks to the end of it to say how long it is: for a view of +/// hundreds of megabytes whose blocks are all read-only, hundreds of +/// microseconds with the address space held against every change of +/// protection. A write fault of the title's on a block that another of its +/// threads is opening asked so ([`writable`]): 91 such questions a frame of +/// 245 microseconds each, 22 ms a frame of the title's threads' time, and the +/// openings themselves (a change of protection each) 235 microseconds behind +/// them; 3.2 ms of every frame's chain (a timeline of the prologue's cell at +/// 38 frames a second, RTX 3090 Ti, Ryzen 9 9950X3D). This asks about one +/// page and walks nothing. `VICTORY_PAGE_ASK=0`: the region, as before. +fn page_protection(at: usize) -> Option { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if !crate::toggled!("VICTORY_PAGE_ASK") { + return None; + } + // SAFETY: plain data, the address asked about in it. + let mut info: PSAPI_WORKING_SET_EX_INFORMATION = unsafe { std::mem::zeroed() }; + info.VirtualAddress = at as *mut _; + // SAFETY: our own process; an array of one record of that size. + let ok = unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), std::ptr::from_mut(&mut info).cast(), size_of_val(&info) as u32) } != 0; + // SAFETY: every form of the answer is these bits. + let flags = unsafe { info.VirtualAttributes.Flags }; + // Bit 0: the page is in memory; bits 4 to 14: its protection then. + (ok && flags & 1 != 0).then(|| ((flags >> 4) & 0x7ff) as u32) +} + /// Whether `at` is committed read-write memory now. fn writable(at: usize) -> bool { use windows_sys::Win32::System::Memory::{ MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery, }; + if let Some(protection) = page_protection(at) { + return protection == PAGE_READWRITE; + } // SAFETY: plain data filled in by the query. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; // SAFETY: a valid out pointer of the right size. From 373b267d7eaba31cfa9abdff2d0687e55e062e92 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund Date: Sat, 28 Nov 2026 04:36:45 -0500 Subject: [PATCH 3/6] Retired objects: a queue to each thread Host objects the title lets go of while a submission may still use them wait in a queue until that submission has finished. There was one queue under one lock, and the eight threads that record the title's lists each let go of thousands of descriptor slots' resources a frame (some 20,000 in all): a push of nanoseconds each, but a thread that finds the lock taken sleeps and is woken 50 microseconds later or more. A profile of the prologue's cell (RTX 3090 Ti, Ryzen 9 9950X3D, Series S profile) had each of those threads 3.3 of the 22 ms a frame it works in that wait, and the thread that prepares submissions 0.7 ms. Now each thread that retires takes one of 32 queues in turn; what finishes a submission looks through all of them. In one run with switches changed by turns the build with this and the two commits before it ran the same scene at 30.47 ms a frame where the build without them had 32.60 (both with VICTORY_CARD_AWAKE=0, diagnostics builds). AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 9165dd03eb85432d691594d76df8a157fa960149) --- crates/victory-gpu/src/host.rs | 45 +++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d1088cc6..4b3fed9f 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -75,7 +75,28 @@ unsafe impl Sync for Host {} /// releases reach the host at once, from its own threads, while the host /// runs a submission: freeing there is a GPU page fault on the freed /// texture (a device hang). -static RETIRED: Mutex> = Mutex::new(std::collections::VecDeque::new()); +/// +/// A queue to each thread that retires, of [`RETIRED_QUEUES`] taken in turn +/// ([`retired`]), each in the order its thread retired. One queue under one +/// lock was what the threads that record the title's lists waited for: eight +/// of them let go of some 20,000 slots' resources a frame, each a push of a +/// few nanoseconds, but a thread that finds the lock taken sleeps and is +/// woken 50 microseconds later or more. 3.3 of the 22 ms a frame each of +/// them was at work, and 0.7 ms of the submitting thread's frame (a profile +/// of the prologue's cell, RTX 3090 Ti, Ryzen 9 9950X3D, Series S profile). +static RETIRED: [Mutex>; RETIRED_QUEUES] = + [const { Mutex::new(std::collections::VecDeque::new()) }; RETIRED_QUEUES]; +const RETIRED_QUEUES: usize = 32; + +/// This thread's queue of [`RETIRED`]. +fn retired() -> &'static Mutex> { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + thread_local! { + static MINE: usize = NEXT.fetch_add(1, Ordering::Relaxed) % RETIRED_QUEUES; + } + // (A thread that is ending has none any more: the first.) + &RETIRED[MINE.try_with(|mine| *mine).unwrap_or(0)] +} /// Submissions started and finished (waited for). static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -469,7 +490,7 @@ pub(crate) fn retire(object: T) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED + retired() .lock() .unwrap_or_else(|e| e.into_inner()) .push_back((started, Retired::Any(Box::new(object)))); @@ -485,7 +506,7 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); + retired().lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); } /// How many submissions later than it could (the last one that may use it @@ -503,18 +524,20 @@ fn bury_lag() -> u64 { } /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The -/// numbers come in order, but for threads that overtake each other: one of -/// those is dropped a little later than it could be. +/// numbers of a queue come in order, but for a submission begun between a +/// thread's two looks ([`retire`]): what follows such a one is dropped a +/// little later than it could be. fn bury(finished: u64) { let finished = finished.saturating_sub(bury_lag()); - let done: Vec<(u64, Retired)> = { - let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + let mut done: Vec<(u64, Retired)> = Vec::new(); + for queue in &RETIRED { + let mut retired = queue.lock().unwrap_or_else(|e| e.into_inner()); let n = retired.iter().take_while(|(at, _)| *at <= finished).count(); - if n == 0 { - return; + if n != 0 { + done.extend(retired.drain(..n)); } - retired.drain(..n).collect() - }; + } + // (Dropped with no queue's lock held: a release each.) drop(done); } From c8062a078927d953cf6b0c2c20f66ae566dc6c99 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund Date: Sat, 28 Nov 2026 04:36:45 -0500 Subject: [PATCH 4/6] Refreshes: the vectorised compare at the two places that still compared word by word `put_changed` and the refresh of a copy's stale pages found their changed runs with `dword_runs`; `word_runs` gives the same runs (its test says so) 32 bytes at a time where the processor has AVX2. The change is trustno1-coder/VIctory-NVIDIA#145 by lido772, who measured 2.61-2.63 -> 2.40-2.41 microseconds a span there. Here it is within the noise of a run (measured together with the build change before it). AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 (cherry picked from commit 3a6b62e5e986206cbefde1cd7b884aaa8fb365aa) --- crates/victory-gpu/src/shadow.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 14dc1605..694c34f4 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2215,7 +2215,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { } return merged.len(); } - let mut runs = dword_runs(at, title, merged, 0); + let mut runs = word_runs(at, title, merged); if runs.len() > 64 { runs = dword_runs(at, title, merged, 32); PUT[3].fetch_add(1, Ordering::Relaxed); @@ -4047,7 +4047,7 @@ impl Shadow { // refresh lie apart. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; let was = crate::host::upcheck::on().then(|| held.to_vec()); - let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) }; + let runs = if whole { vec![(0, n)] } else { word_runs(at, held, title) }; for &(a, len) in &runs { held[a..a + len].copy_from_slice(&title[a..a + len]); self.changed(at - start + a, at - start + a + len); From 0dd1e9fab2f9d6ddc4d7c04f112c446e0f48148a Mon Sep 17 00:00:00 2001 From: Kyle Soderlund Date: Fri, 27 Nov 2026 16:58:22 -0500 Subject: [PATCH 5/6] Shaders: the console's waterfall over a first-lane table offset is proven by its shape where the per-lane form cannot follow it The console compiler loops over a per-lane descriptor by reading the first active lane's table offset, narrowing EXEC to the lanes with the same one, loading that entry and dropping those lanes. `track` makes each lane load its own entry when `Tracer::waterfall` proves the loop. In the title's programs it mostly cannot: over all 25,760 programs it emits, 44,874 such loops were refused, 37,605 of them because the per-lane form could not show that the compares select the access's lanes and 209 because it could not show that the retry keeps the lanes still waiting. In a wave of 64 run as two host waves of 32, every pass of an unproven loop exchanges the first lane's value and the mask between the halves: four group barriers a pass. `Tracer::waterfall_shape` proves the loop by its exact shape instead, only where `waterfall` refused: one block that branches to itself, with nothing in it but the first-lane reads, `v_cmpx_eq` of each with the same lane value, the table loads, waits, accesses that only read, and `s_andn2_wrexec` of a mask T with itself. T is shown to be EXEC on every entry from the phis (a move of the loop's own entry EXEC from outside; the same retry on the back edge), and the first-lane value is read nowhere past the loop. It proves 32,106 of the refused loops. The same programs are emitted as before, and the DXIL validator gives the same results as before for all of them. Measured in the prologue's cell (RTX 3090 Ti, Series S profile, one run each way unless said): where the card is the limit the frame gets 2.5 to 4 ms shorter. With the title's own upscaler (#68), 30.8 fps before and 33.3, 32.9 and 32.0 after; with DLSS Quality and FSR 3 frame generation, 27.0 rendered before and 30.8 after. On main alone without DLSS, where the translated FSR 4 path keeps the preparing thread at 27 to 28 ms a frame, 28.5 before and 28.7 after. The costliest program of the frame, vfx_proj_decal_vbuffer:CS_ProjDecalReduceClassification_Scalarized (4.1 ms a frame in a timing run), has 27 such loops; its DXIL goes from 149 group barriers to 41. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 37b0acebc4368e5e6603c0c5dad370a28ae55e36) --- crates/victory-shader/src/resource.rs | 347 +++++++++++++++++++++++++- 1 file changed, 346 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ddc03ddd..ae16c51e 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -363,7 +363,13 @@ pub fn track( for (block, (accesses, mut reads, loads)) in offset_at { reads.sort_unstable(); reads.dedup(); - if let Ok(proof) = t.waterfall(block, &accesses, &reads) { + // Where the per-lane form cannot follow the loop, its exact shape + // still proves it ([`Tracer::waterfall_shape`]). + let proof = t + .waterfall(block, &accesses, &reads) + .ok() + .or_else(|| t.waterfall_shape(block, &accesses, &reads, &loads)); + if let Some(proof) = proof { out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); out.waterfall.loads.extend(loads); @@ -2128,6 +2134,213 @@ impl<'a> Tracer<'a> { Ok(out) } + /// The console compiler's waterfall over a first-lane table offset, by + /// its exact shape, where [`Self::waterfall`] cannot follow the lanes + /// (its per-lane form loses the relation of the two lane masks around + /// the loop in larger programs). The loop is one block that branches to + /// itself with `s_cbranch_execnz`, and holds nothing but: + /// + /// - `v_readfirstlane_b32 sX, vY` of a value set before the loop, under + /// EXEC as the loop found it; + /// - `v_cmpx_eq_u32`/`_i32 exec, sX, vY` of the same two values, without + /// modifiers: EXEC becomes the lanes whose offset is the first lane's; + /// - the table loads at those offsets (`loads`), waits and `s_nop`; + /// - the accesses that use them, which only read (`buffer_load_*`, + /// `image_load*`, `image_sample*`, `image_gather*`), under that EXEC; + /// - `s_andn2_wrexec` of a mask T with itself (EXEC and T become T and + /// not EXEC), then the branch. + /// + /// And T is EXEC on every entry to the loop: from outside, T's value is + /// a move of the very EXEC value the loop starts with; around the back + /// edge both are what that one `s_andn2_wrexec` wrote. So each pass + /// serves the waiting lanes with the first one's offset, drops exactly + /// those, and the loop ends when none waits: every lane makes its own + /// access once, with its own entry, which is what the per-lane load + /// does. + fn waterfall_shape( + &self, + b: usize, + accesses: &[usize], + reads: &[Value], + loads: &[Site], + ) -> Option { + let block = &self.p.blocks[b]; + let wave64 = self.p.wave64; + let halves: &[u8] = if wave64 { &[0, 1] } else { &[0] }; + if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) + || block.preds.len() != 2 + { + return None; + } + let back = block.preds.iter().position(|&p| p == b)?; + let entry = 1 - back; + let (exit, body) = block.insts.split_last()?; + if exit.name() != "s_cbranch_execnz" { + return None; + } + let (retry, body) = body.split_last()?; + let wrexec = if wave64 { + "s_andn2_wrexec_b64" + } else { + "s_andn2_wrexec_b32" + }; + if retry.name() != wrexec { + return None; + } + // T: the mask the retry reads and writes besides EXEC. + let t = retry.writes.iter().find_map(|&(reg, _)| match reg { + Reg::S(code) if code != EXEC && code != EXEC + 1 => Some(code), + _ => None, + })?; + let t = t - t % 2 * u8::from(wave64); + let phi = |reg: u8| block.phis.iter().find(|p| p.reg == Reg::S(reg)); + let mut head_exec = Vec::new(); + for &k in halves { + let (pe, pt) = (phi(EXEC + k)?, phi(t + k)?); + // Around the back edge: both what the retry wrote, from T as the + // loop found it. + if pe.args[back] != retry.write(Reg::S(EXEC + k))? + || pt.args[back] != retry.write(Reg::S(t + k))? + || retry.read(Reg::S(t + k))? != pt.value + { + return None; + } + // From outside: T is a move of the EXEC the loop is entered with. + let (tb, ti) = self.defs[pt.args[entry].0 as usize]?; + let mov = self.inst((tb, ti)); + let moves = if wave64 { "s_mov_b64" } else { "s_mov_b32" }; + if mov.name() != moves || mov.read(Reg::S(EXEC + k))? != pe.args[entry] { + return None; + } + head_exec.push(pe.value); + } + let exec_is = |inst: &Inst, values: &[Value]| { + halves + .iter() + .zip(values) + .all(|(&k, &v)| inst.read(Reg::S(EXEC + k)) == Some(v)) + }; + let mut out = Waterfall::default(); + let mut selected: Option> = None; + // The lane value each first-lane read took, by the read's result. + let mut read_from: Vec<(Value, Value)> = Vec::new(); + for (i, inst) in body.iter().enumerate() { + let name = inst.name(); + let site = (b, i); + if name == "s_nop" || name.starts_with("s_waitcnt") { + continue; + } + if name == "v_readfirstlane_b32" { + // Before the compares, under the loop's own EXEC. + if selected.is_some() || !exec_is(inst, &head_exec) { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let Some(&Operand::Vector { reg, .. }) = f.src.first() else { + return None; + }; + let lane = inst.read(Reg::V(reg))?; + // Set before the loop: the same in every pass. + if self.phis[lane.0 as usize].is_some_and(|(pb, _)| pb == b) + || self.defs[lane.0 as usize].is_some_and(|(db, _)| db == b) + { + return None; + } + let &(_, got) = inst.writes.first()?; + read_from.push((got, lane)); + continue; + } + if name == "v_cmpx_eq_u32" || name == "v_cmpx_eq_i32" { + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 + || f.neg != 0 + || f.opsel != 0 + || f.clamp + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + // Compares narrow EXEC one after another. + let before = selected.clone().unwrap_or_else(|| head_exec.clone()); + if !exec_is(inst, &before) { + return None; + } + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + return None; + }; + let pair = |first: &Operand, own: &Operand| -> Option { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = + (first, own) + else { + return None; + }; + let x = inst.read(Reg::S(code))?; + let lane = inst.read(Reg::V(reg))?; + read_from + .iter() + .any(|&(got, from)| got == x && from == lane) + .then_some(x) + }; + let x = pair(a, c).or_else(|| pair(c, a))?; + let narrowed = halves + .iter() + .map(|&k| inst.write(Reg::S(EXEC + k))) + .collect::>>()?; + selected = Some(narrowed); + out.compares.push(site); + if !out.reads.contains(&x) { + out.reads.push(x); + } + continue; + } + let sel = selected.as_deref()?; + if loads.contains(&site) { + continue; + } + let reads_only = name.starts_with("buffer_load") + || name.starts_with("image_load") + || name.starts_with("image_sample") + || name.starts_with("image_gather"); + if accesses.contains(&i) && reads_only && exec_is(inst, sel) { + continue; + } + return None; + } + // The retry takes T and not the EXEC the compares left. + let sel = selected?; + if !exec_is(retry, &sel) { + return None; + } + // Every offset read is one a compare made the lane's own, and every + // access was seen. + if reads.iter().any(|v| !out.reads.contains(v)) || accesses.iter().any(|&i| i >= body.len()) + { + return None; + } + // Read nowhere else: made the lane's own, a first-lane value must + // not reach code past the loop, which would see the last pass's. + for (ob, other) in self.p.blocks.iter().enumerate() { + let carried = other + .phis + .iter() + .any(|p| p.args.iter().any(|a| out.reads.contains(a))); + let read_there = ob != b + && other + .insts + .iter() + .any(|inst| inst.reads.iter().any(|(_, v)| out.reads.contains(v))); + if carried || read_there { + return None; + } + } + Some(out) + } + /// Consecutive dwords of one scalar load. fn loaded(&self, words: &[Term]) -> Option { let Term::Value(v0) = words[0] else { @@ -3382,6 +3595,138 @@ pub(crate) mod tests { assert_eq!(r.waterfall.loads, [load]); } + /// [`WATERFALL_INDEXED_WAVE32`] as a wave of 64 runs it: EXEC saved + /// and the lanes still waiting kept in SGPR pairs, the retry + /// `s_andn2_wrexec_b64`. + fn waterfall_indexed_wave64() -> Vec { + let mut w = WATERFALL_INDEXED_WAVE32.to_vec(); + for (from, to) in [ + (0xBE97_037E, 0xBE96_047E), // s_mov_b64 s[22:23], exec + (0xBE95_037E, 0xBE98_047E), // s_mov_b64 s[24:25], exec + (0xBE95_4715, 0xBE98_3A18), // s_andn2_wrexec_b64 s[24:25], s[24:25] + (0xBEFE_0317, 0xBEFE_0416), // s_mov_b64 exec, s[22:23] + ] { + let at = word_at(&w, from); + w[at] = to; + } + w + } + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_is_one_in_a_wave_of_64() { + let r = waterfall(&waterfall_indexed_wave64(), true).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Loaded { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + assert_eq!(r.waterfall.compares.len(), 1); + assert_eq!(r.waterfall.reads.len(), 1); + assert_eq!(r.waterfall.loads, [load]); + } + + /// [`Tracer::waterfall_shape`] on the one loop of `words`, with what + /// [`track`] would hand it: the loop's table loads, its first-lane reads + /// and its buffer and image accesses. + fn by_shape(words: &[u32], wave64: bool) -> Option { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, wave64, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + let lanes = lanes(&p); + let t = Tracer::new(&p, &layout, HwStage::Cs, lanes.as_ref()).unwrap(); + let b = (0..p.blocks.len()) + .find(|&b| matches!(p.blocks[b].exit, Exit::Branch { taken, .. } if taken == b)) + .unwrap(); + let insts = &p.blocks[b].insts; + let loads: Vec = (0..insts.len()) + .filter(|&i| insts[i].name().starts_with("s_load_")) + .map(|i| (b, i)) + .collect(); + let reads: Vec = insts + .iter() + .filter(|i| i.name() == "v_readfirstlane_b32") + .filter_map(|i| i.writes.first().map(|w| w.1)) + .collect(); + let accesses: Vec = (0..insts.len()) + .filter(|&i| { + matches!( + insts[i].fields, + Fields::Buffer { .. } | Fields::Image { .. } + ) + }) + .collect(); + t.waterfall_shape(b, &accesses, &reads, &loads) + } + + /// [`WATERFALL_INDEXED_WAVE32`] or [`waterfall_indexed_wave64`] with + /// words replaced. + fn indexed_with(wave64: bool, changes: &[(u32, u32)]) -> Vec { + let mut w = if wave64 { + waterfall_indexed_wave64() + } else { + WATERFALL_INDEXED_WAVE32.to_vec() + }; + for &(from, to) in changes { + let at = word_at(&w, from); + w[at] = to; + } + w + } + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_holds_by_its_shape() { + for wave64 in [false, true] { + let shape = by_shape(&indexed_with(wave64, &[]), wave64) + .unwrap_or_else(|| panic!("wave64 {wave64}")); + assert_eq!(shape.compares.len(), 1, "wave64 {wave64}"); + assert_eq!(shape.reads.len(), 1, "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_loop_with_other_work_in_it_is_none_by_shape() { + for wave64 in [false, true] { + // s_waitcnt vmcnt(0) in the loop becomes v_mov_b32 v20, v7. + let words = indexed_with(wave64, &[(0xBF8C_3F70, 0x7E28_0307)]); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_comparing_another_lane_value_is_none_by_shape() { + for wave64 in [false, true] { + // v_cmpx_eq_u32 exec, s20, v0: the lane's index, not the offset + // the first lane's was read from (v7). + let words = indexed_with(wave64, &[(0x7DA4_0E14, 0x7DA4_0014)]); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_whose_lanes_to_do_are_not_exec_is_none_by_shape() { + // The mask of lanes still to do starts as every lane, not EXEC. + let words = indexed_with(false, &[(0xBE95_037E, 0xBE95_03C1)]); // s_mov_b32 s21, -1 + assert!(by_shape(&words, false).is_none()); + let words = indexed_with(true, &[(0xBE98_047E, 0xBE98_04C1)]); // s_mov_b64 s[24:25], -1 + assert!(by_shape(&words, true).is_none()); + } + + #[test] + fn a_first_lane_offset_read_after_its_loop_is_none_by_shape() { + for wave64 in [false, true] { + // The store after the loop becomes v_mov_b32 v20, s20 (the + // first lane's offset of the last pass) and s_nop. + let words = indexed_with( + wave64, + &[(0xE070_1000, 0x7E28_0214), (0x800A_0C10, 0xBF80_0000)], + ); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the From 7d5ffdb5fd5ea7445eac46b9f83167b90ce2b8b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:23:57 +0000 Subject: [PATCH 6/6] Neo picks: gate PAGE_ASK, RETIRED_QUEUES, WORD_RUNS, WATERFALL_SHAPE behind switches (off by default) With none of the switches set the behaviour is that of f4b48ad: - VICTORY_PAGE_ASK=1: a write fault asks QueryWorkingSetEx about its one page (Neo 0fb1e38; on by default there). - VICTORY_RETIRED_QUEUES=1: 32 per-thread retired queues (Neo 9165dd0); off: queue 0 only. - VICTORY_WORD_RUNS=1: AVX2 word_runs at the two refresh sites (Neo 3a6b62e); off: dword_runs as before. - VICTORY_WATERFALL_SHAPE=1: translator proves waterfall loops by shape (Neo 37b0ace); joins the shader cache key. Switch gating written by DeepSeek (deepseek-v4-pro). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FLuVRmoPqty3gMWAGg1Bbv --- crates/victory-gpu/src/host.rs | 5 +++++ crates/victory-gpu/src/shader_cache.rs | 1 + crates/victory-gpu/src/shadow.rs | 10 ++++++++-- crates/victory-gpu/src/watch.rs | 4 +++- crates/victory-shader/src/resource.rs | 8 +++++++- 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4b3fed9f..52454532 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -90,6 +90,11 @@ const RETIRED_QUEUES: usize = 32; /// This thread's queue of [`RETIRED`]. fn retired() -> &'static Mutex> { + // `VICTORY_RETIRED_QUEUES=1`: a queue to each thread; off: one queue, as before. + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| crate::switch::on("VICTORY_RETIRED_QUEUES")) { + return &RETIRED[0]; + } static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); thread_local! { static MINE: usize = NEXT.fetch_add(1, Ordering::Relaxed) % RETIRED_QUEUES; diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index b291e117..f11ad1d7 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -75,6 +75,7 @@ fn build() -> [u8; 32] { "VICTORY_MESH_OUTPUT_STRICT", "VICTORY_BVH_FENCES", "VICTORY_BVH_BOUNDS", + "VICTORY_WATERFALL_SHAPE", ] { bytes.extend_from_slice(name.as_bytes()); bytes.push(b'='); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 694c34f4..22b74a1b 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2113,6 +2113,12 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, /// [`dword_runs`] with no gap, the fast way where it can be: a frame compares /// 12 MB this way and finds 80,000 runs. +/// `VICTORY_WORD_RUNS=1`: word_runs; off: dword_runs, as before. +fn word_runs_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_WORD_RUNS")) +} + fn word_runs(at: usize, title: &[u8], held: &[u8]) -> Vec<(usize, usize)> { #[cfg(target_arch = "x86_64")] if at % 4 == 0 && title.len() % 4 == 0 && title.len() == held.len() && std::arch::is_x86_feature_detected!("avx2") { @@ -2215,7 +2221,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { } return merged.len(); } - let mut runs = word_runs(at, title, merged); + let mut runs = if word_runs_on() { word_runs(at, title, merged) } else { dword_runs(at, title, merged, 0) }; if runs.len() > 64 { runs = dword_runs(at, title, merged, 32); PUT[3].fetch_add(1, Ordering::Relaxed); @@ -4047,7 +4053,7 @@ impl Shadow { // refresh lie apart. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; let was = crate::host::upcheck::on().then(|| held.to_vec()); - let runs = if whole { vec![(0, n)] } else { word_runs(at, held, title) }; + let runs = if whole { vec![(0, n)] } else if word_runs_on() { word_runs(at, held, title) } else { dword_runs(at, held, title, 0) }; for &(a, len) in &runs { held[a..a + len].copy_from_slice(&title[a..a + len]); self.changed(at - start + a, at - start + a + len); diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 813b5aa7..15431936 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -2990,7 +2990,9 @@ pub(crate) fn install() { fn page_protection(at: usize) -> Option { use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; use windows_sys::Win32::System::Threading::GetCurrentProcess; - if !crate::toggled!("VICTORY_PAGE_ASK") { + /// `VICTORY_PAGE_ASK=1`: ask about the one page; off: the region, as before. + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| crate::switch::on("VICTORY_PAGE_ASK")) { return None; } // SAFETY: plain data, the address asked about in it. diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ae16c51e..323a7585 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -195,6 +195,12 @@ pub struct Waterfall { pub loads: Vec, } +/// `VICTORY_WATERFALL_SHAPE=1`: waterfall_shape; off: waterfall, as before. +pub fn waterfall_shape_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WATERFALL_SHAPE").is_some_and(|v| v != "0")) +} + /// Traces every descriptor and scalar address of `p`, which runs as /// `stage`, to the root parameters in `layout`. Fails on the first one it /// cannot trace. `lanes`, `p` as one lane runs it, tells which paths the @@ -368,7 +374,7 @@ pub fn track( let proof = t .waterfall(block, &accesses, &reads) .ok() - .or_else(|| t.waterfall_shape(block, &accesses, &reads, &loads)); + .or_else(|| if waterfall_shape_on() { t.waterfall_shape(block, &accesses, &reads, &loads) } else { None }); if let Some(proof) = proof { out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads);