From d1c412c57b94267ef7d8c5dc1897e62e68c5ac42 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 10:39:25 -0600 Subject: [PATCH 01/31] A slot written with another texture goes on showing one that can stand for it (VICTORY_KEEP_SHOWN=1; 0: black, then grey); textures that pop are counted (VICTORY_POP_WATCH) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 172 ++++++++++- crates/victory-gpu/src/host.rs | 16 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/popwatch.rs | 344 ++++++++++++++++++++++ 4 files changed, 527 insertions(+), 7 deletions(-) create mode 100644 crates/victory-gpu/src/popwatch.rs diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2e1c06a..47e7d5c 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2007,7 +2007,11 @@ impl HostHeap { } } let old = view_at(shown as u32, (shown >> 32) as u32); - if shown == 0 || !old.is_some_and(|old| same_placed_texture(&old, &view)) { + let kept = old.is_some_and(|old| match kin(&old, &view) { + Kin::Same => true, + kin => kin.kept(keep_shown()), + }); + if shown == 0 || !kept { #[cfg(feature = "diagnostics")] note_before(index, shown, "neutral"); self.quick_is(index, 0); @@ -2862,13 +2866,26 @@ impl HostHeap { // one and uploads what it shows. Made null here, the texture // read as nothing for as long as it waited in the queue, every // time it got sharper. + let shown = made[index as usize]; if later && keep_views() - && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32) - .is_some_and(|old| same_placed_texture(&old, &view)) + && let Some(old) = view_at(shown as u32, (shown >> 32) as u32) { - KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - return Some(view); + let kin = kin(&old, &view); + if kin == Kin::Same { + KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return Some(view); + } + // And of another texture that can stand for it + // ([`keep_shown`]): black, then grey for a frame or two is + // what popped. + if is_texture_view(&old) { + let kept = kin.kept(keep_shown()); + rewritten(kin, kept); + if kept { + return Some(view); + } + } } #[cfg(feature = "diagnostics")] if !self.sampler && is_texture_view(&view) { @@ -3964,6 +3981,121 @@ fn keep_views() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0")) } +/// What the texture view a slot is written with has to do with the one it +/// shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kin { + /// A view of the same placed texture ([`same_placed_texture`]). + Same, + /// A texture of the same description placed elsewhere (moved, or one of + /// its kind). + Moved, + /// One of the same format and shape in another size: the same texture + /// with more or fewer levels, as a title streams it. + Sized, + /// A view of the same dimension, of another texture. + Other, + /// A view no shader that reads the one can read. + None, +} + +impl Kin { + /// Whether the slot goes on showing what it shows, by [`keep_shown`]. + fn kept(self, keep: u8) -> bool { + match self { + Kin::Same => true, + Kin::Moved | Kin::Sized => keep >= 1, + Kin::Other => keep >= 2, + Kin::None => false, + } + } +} + +/// [`Kin`] of the view `old`, which a slot shows, and `new`. +fn kin(old: &View, new: &View) -> Kin { + if same_placed_texture(old, new) { + return Kin::Same; + } + if let (View::Placed(false, a, from), View::Placed(false, b, to)) = (old, new) { + if a[0] == 1 || b[0] == 1 || from[1] != to[1] { + return Kin::None; + } + // (Width, 64 bits, height, depth and levels, format: words 4 to 8.) + if a[0] == b[0] && a[2..13] == b[2..13] { + return Kin::Moved; + } + let (wide, high) = ([a[4], b[4]].map(u64::from), [a[6], b[6]].map(u64::from)); + return if from[0] == to[0] && a[0] == b[0] && wide[0] * high[1] == wide[1] * high[0] { + Kin::Sized + } else { + Kin::Other + }; + } + let dimension = |view: &View| match view { + View::Placed(false, resource, desc) if resource[0] != 1 => desc[1], + View::Shader(r, Some(desc)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => desc[1], + _ => 0, + }; + match (dimension(old), dimension(new)) { + (0, _) | (_, 0) => Kin::None, + (a, b) if a == b => Kin::Other, + _ => Kin::None, + } +} + +/// Whether a slot that is written with a view of another texture goes on +/// showing the one it shows until the new one is made and its upload has run +/// (`VICTORY_KEEP_SHOWN`): 0: never, it reads as zeros, then as the neutral +/// texture; 1: one of the same kind in another place or size; 2: any of the +/// same dimension. +fn keep_shown() -> u8 { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_KEEP_SHOWN") { + return if on { 2 } else { 0 }; + } + static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + *KEEP.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1)) +} + +/// Slots that showed a texture and were written with a view of another, +/// since the start, by [`Kin`] (moved, sized, other, none), and those of +/// them that kept what they showed. +static REWRITTEN: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +fn rewritten(kin: Kin, kept: bool) { + use std::sync::atomic::Ordering::Relaxed; + let class = match kin { + Kin::Moved | Kin::Same => 0, + Kin::Sized => 1, + Kin::Other => 2, + Kin::None => 3, + }; + REWRITTEN[class].fetch_add(1, Relaxed); + REWRITTEN[4].fetch_add(u64::from(kept), Relaxed); + let n: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum(); + if n.is_multiple_of(5000) { + tracing::info!( + "slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN)", + REWRITTEN[0].load(Relaxed), + REWRITTEN[1].load(Relaxed), + REWRITTEN[2].load(Relaxed), + REWRITTEN[3].load(Relaxed), + REWRITTEN[4].load(Relaxed) + ); + } +} + +/// For `crate::popwatch`, since the start: slots made null as they were +/// written with another texture, such that kept the old one, slots given the +/// neutral texture, slots made null as their memory was another's. +#[cfg(feature = "diagnostics")] +pub(crate) fn pop_causes() -> [u64; 4] { + use std::sync::atomic::Ordering::Relaxed; + let all: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum(); + let kept = REWRITTEN[4].load(Relaxed); + [all.saturating_sub(kept), kept, LATE[3].load(Relaxed), STALE[0].load(Relaxed)] +} + /// Whether a slot already made from its record is told so without the lock /// (`VICTORY_QUICK_MIRROR=0`: with it, as before). fn quick_mirror() -> bool { @@ -4373,6 +4505,36 @@ mod tests { assert!(!same_placed_texture(&low, &View::Shader(0, None))); } + /// What may stand for a texture that is not there yet: one of its kind in + /// another place or size; another one only if asked; nothing a shader + /// cannot read in its place. + #[test] + fn a_slot_shows_on_what_can_stand_for_its_new_texture() { + let texture = [3, 0, 0, 0, 512, 0, 256, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let view = |resource: [u32; 14], format: u32, dimension: u32, address: u32| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[10], desc[11]) = (format, dimension, address, 0xb); + View::Placed(false, resource, desc) + }; + let old = view(texture, 98, 4, 0x1000_0000); + let mut twice = texture; + (twice[4], twice[6], twice[7]) = (1024, 512, 0x9_0001); + let mut square = texture; + square[6] = 512; + let mut buffer = texture; + buffer[0] = 1; + assert_eq!(kin(&old, &view(texture, 98, 4, 0x1000_0000)), Kin::Same); + assert_eq!(kin(&old, &view(texture, 98, 4, 0x2000_0000)), Kin::Moved); + assert_eq!(kin(&old, &view(twice, 98, 4, 0x2000_0000)), Kin::Sized); + assert_eq!(kin(&old, &view(square, 98, 4, 0x2000_0000)), Kin::Other); + assert_eq!(kin(&old, &view(twice, 83, 4, 0x2000_0000)), Kin::Other); + assert_eq!(kin(&old, &view(texture, 98, 9, 0x2000_0000)), Kin::None); + assert_eq!(kin(&old, &view(buffer, 98, 1, 0x2000_0000)), Kin::None); + for (kin, kept) in [(Kin::Same, [true; 3]), (Kin::Moved, [false, true, true]), (Kin::Sized, [false, true, true]), (Kin::Other, [false, false, true]), (Kin::None, [false; 3])] { + assert_eq!([0, 1, 2].map(|keep| kin.kept(keep)), kept, "{kin:?}"); + } + } + /// A constant buffer view larger than the host takes is cut to what it /// takes: the device, which such a view removes, stays. #[test] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 507a79d..66e42e7 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8363,6 +8363,8 @@ impl Host { .flatten(); #[cfg(feature = "diagnostics")] let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + #[cfg(feature = "diagnostics")] + let watched = crate::popwatch::take(&self.device, list, texture); #[cfg(not(feature = "diagnostics"))] let _ = frame; list.ResourceBarrier(&[ @@ -8374,13 +8376,23 @@ impl Host { ), ]); copy.close(); - match slot { + let flown = match slot { Some(i) => { let flown = self.execute_own(copy); p.ahead[i].1 = flown; + flown } - None => self.execute(&[copy]), + None => { + self.execute(&[copy]); + 0 + } + }; + #[cfg(feature = "diagnostics")] + if let Some(taken) = watched { + crate::popwatch::sent(taken, flown, frame); } + #[cfg(not(feature = "diagnostics"))] + let _ = flown; #[cfg(feature = "diagnostics")] if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 29947a7..e09313b 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -46,6 +46,8 @@ pub mod pipeline; mod picked; #[cfg(windows)] mod pool; +#[cfg(all(windows, feature = "diagnostics"))] +mod popwatch; #[cfg(windows)] mod primitive; pub mod query; diff --git a/crates/victory-gpu/src/popwatch.rs b/crates/victory-gpu/src/popwatch.rs new file mode 100644 index 0000000..fbba71e --- /dev/null +++ b/crates/victory-gpu/src/popwatch.rs @@ -0,0 +1,344 @@ +//! Diagnostics: textures that pop. `VICTORY_POP_WATCH=-[,-..]` +//! (seconds since the start): every presented frame in those times is read +//! back, made small on a thread of its own and compared with its neighbours, +//! block by block. Counted and logged: +//! - blips: blocks that one frame shows otherwise than the frames before and +//! after it, which agree (a texture black, grey or another one for a frame); +//! - steps: blocks that change from one frame to the next and stay so, while +//! most of the picture does not move. +//! +//! `VICTORY_POP_FOLDER=`: the three pictures around a frame with +//! blips (at most 200 times) are saved there, 640 wide; with +//! `VICTORY_POP_ALL=1` every frame's is. + +use std::collections::VecDeque; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock, mpsc}; + +use windows::Win32::Graphics::Direct3D12::*; + +/// A small picture: so many pixels wide and high. +const WIDE: usize = 640; +const HIGH: usize = 360; +/// Pixels per side of a block. +const BLOCK: usize = 16; +/// A block changed: so much in the mean of its pixels' largest channel change. +const CHANGED: f32 = 10.0; +/// A block stayed. +const STAYED: f32 = 4.0; + +/// `10-20,30-40` as seconds. +fn parse(text: &str) -> Vec<(f64, f64)> { + text.split(',') + .filter_map(|part| { + let (from, to) = part.trim().split_once('-')?; + Some((from.trim().parse().ok()?, to.trim().parse().ok()?)) + }) + .collect() +} + +fn asked() -> &'static [(f64, f64)] { + static ASKED: OnceLock> = OnceLock::new(); + ASKED.get_or_init(|| std::env::var("VICTORY_POP_WATCH").map(|v| parse(&v)).unwrap_or_default()) +} + +/// Whether frames are watched now. +pub(crate) fn on() -> bool { + let asked = asked(); + if asked.is_empty() { + return false; + } + let now = crate::host::now_ms() as f64 / 1e3; + asked.iter().any(|&(from, to)| now >= from && now < to) +} + +/// A frame on its way back. +pub(crate) struct Taken { + buffer: ID3D12Resource, + footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +} + +struct Job { + frame: u64, + taken: Taken, + /// The submission that copies it. + flown: u64, + ms: u64, + causes: [u64; 4], + phase: Option, +} + +/// Read-back buffers not in use. +static FREE: Mutex> = Mutex::new(Vec::new()); +/// Frames on their way. +static WAITING: AtomicU64 = AtomicU64::new(0); + +/// Records the read-back of `texture` (in the copy-source state). +pub(crate) fn take(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) -> Option { + if !on() || WAITING.load(Relaxed) > 8 { + return None; + } + let free = FREE.lock().unwrap_or_else(|e| e.into_inner()).pop(); + let Some(taken) = free else { + let (buffer, footprint) = crate::capture::read_back(device, list, texture)?; + return Some(Taken { buffer, footprint }); + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&taken.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: taken.footprint }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + // SAFETY: an open list, live resources. + unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + Some(taken) +} + +/// The list with `taken` went to the card as submission `flown` (0: it has +/// run). `frame`: the frame it shows. +pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) { + static THREAD: OnceLock>> = OnceLock::new(); + let Some(to) = THREAD.get_or_init(|| { + let (to, from) = mpsc::channel::(); + std::thread::Builder::new().name("pop watch".into()).spawn(move || watch(&from)).ok().map(|_| to) + }) else { + return; + }; + WAITING.fetch_add(1, Relaxed); + let job = Job { + frame, + taken, + flown, + ms: crate::host::now_ms(), + causes: crate::descriptor::host::pop_causes(), + phase: crate::ab::pick("VICTORY_KEEP_SHOWN"), + }; + let _ = to.send(job); +} + +/// What was seen of the frames so far. +#[derive(Default)] +struct Seen { + frames: u64, + blips: u64, + blip_frames: u64, + steps: u64, + still: u64, +} + +struct Picture { + frame: u64, + ms: u64, + causes: [u64; 4], + phase: Option, + rgb: Vec, + /// Per block: how much it differs from the frame before. + changed: Vec, + saved: bool, +} + +/// Per block, the mean of the pixels' largest channel change. +fn differ(a: &[u8], b: &[u8]) -> Vec { + let (across, down) = (WIDE / BLOCK, HIGH / BLOCK); + let mut out = vec![0.0; across * down]; + for (n, sum) in out.iter_mut().enumerate() { + let (bx, by) = (n % across * BLOCK, n / across * BLOCK); + let mut total = 0u32; + for y in by..by + BLOCK { + let at = (y * WIDE + bx) * 3; + let (ra, rb) = (&a[at..at + BLOCK * 3], &b[at..at + BLOCK * 3]); + total += ra + .chunks_exact(3) + .zip(rb.chunks_exact(3)) + .map(|(p, q)| p.iter().zip(q).map(|(x, y)| u32::from(x.abs_diff(*y))).max().unwrap_or(0)) + .sum::(); + } + *sum = total as f32 / (BLOCK * BLOCK) as f32; + } + out +} + +/// The blips of `now` between `before` and `after`, and its steps (the frame +/// before `before` had `quiet` changes): numbers of blocks. `None` for the +/// steps if the picture moves. +fn judge(before: &[u8], now: &[u8], after: &[u8], quiet: &[f32]) -> (usize, Option) { + let (one, two, across) = (differ(before, now), differ(now, after), differ(before, after)); + let blips = (0..one.len()) + .filter(|&n| one[n] > CHANGED && two[n] > CHANGED && across[n] < STAYED && across[n] * 3.0 < one[n]) + .count(); + let still = one.iter().filter(|&&d| d < 3.0).count() * 10 >= one.len() * 7; + let steps = still.then(|| { + (0..one.len()).filter(|&n| one[n] > CHANGED && two[n] < STAYED && quiet.get(n).is_some_and(|&d| d < STAYED)).count() + }); + (blips, steps) +} + +/// `width * height` 8-bit RGBA (or BGRA) pixels made small. +fn small(rows: &[u8], width: usize, height: usize, pitch: usize, bgra: bool) -> Vec { + let mut out = Vec::with_capacity(WIDE * HIGH * 3); + for y in 0..HIGH { + for x in 0..WIDE { + let mut sum = [0u32; 3]; + for sy in 0..3 { + for sx in 0..3 { + let px = ((x * 3 + sx) * 2 + 1) * width / (WIDE * 6); + let py = ((y * 3 + sy) * 2 + 1) * height / (HIGH * 6); + let p = &rows[py.min(height - 1) * pitch + px.min(width - 1) * 4..][..3]; + for (s, v) in sum.iter_mut().zip(p) { + *s += u32::from(*v); + } + } + } + let c = sum.map(|s| (s / 9) as u8); + out.extend(if bgra { [c[2], c[1], c[0]] } else { c }); + } + } + out +} + +fn folder() -> Option<&'static PathBuf> { + static FOLDER: OnceLock> = OnceLock::new(); + FOLDER + .get_or_init(|| { + let folder = PathBuf::from(std::env::var_os("VICTORY_POP_FOLDER")?); + std::fs::create_dir_all(&folder).ok()?; + Some(folder) + }) + .as_ref() +} + +fn save(p: &mut Picture) { + if p.saved { + return; + } + p.saved = true; + if let Some(folder) = folder() { + let png = crate::capture::png(WIDE as u32, HIGH as u32, &p.rgb); + let _ = std::fs::write(folder.join(format!("{:07}-f{}.png", p.ms, p.frame)), png); + } +} + +fn watch(from: &mpsc::Receiver) { + let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1"); + let mut last: VecDeque = VecDeque::new(); + let mut seen: [Seen; 2] = Default::default(); + let mut told = crate::host::now_ms(); + let mut sets = 0; + while let Ok(job) = from.recv() { + while crate::host::submissions().1 < job.flown { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let f = job.taken.footprint.Footprint; + let (rgba, bgra) = (matches!(f.Format.0, 27..=29), matches!(f.Format.0, 87 | 90 | 91)); + let mut data = std::ptr::null_mut(); + // SAFETY: the copy has run; the mapping spans the footprint's rows. + let rgb = unsafe { + if !(rgba || bgra) || job.taken.buffer.Map(0, None, Some(&mut data)).is_err() { + WAITING.fetch_sub(1, Relaxed); + continue; + } + let rows = std::slice::from_raw_parts(data.cast::(), f.RowPitch as usize * f.Height as usize); + let rgb = small(rows, f.Width as usize, f.Height as usize, f.RowPitch as usize, bgra); + job.taken.buffer.Unmap(0, None); + rgb + }; + FREE.lock().unwrap_or_else(|e| e.into_inner()).push(job.taken); + WAITING.fetch_sub(1, Relaxed); + // Frames that follow each other only. + if last.back().is_some_and(|p| p.frame + 1 != job.frame) { + last.clear(); + } + let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default(); + let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase); + last.push_back(Picture { frame, ms, causes, phase, rgb, changed, saved: false }); + if all && let Some(p) = last.back_mut() { + save(p); + } + if last.len() > 4 { + last.pop_front(); + } + if let [first, before, now, after] = last.make_contiguous() { + let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed); + let side = &mut seen[usize::from(now.phase.unwrap_or(false))]; + side.frames += 1; + side.blips += blips as u64; + side.blip_frames += u64::from(blips > 0); + side.still += u64::from(steps.is_some()); + side.steps += steps.unwrap_or(0) as u64; + if blips > 0 || steps.is_some_and(|s| s > 0) { + let since: Vec = now.causes.iter().zip(&first.causes).map(|(a, b)| a.saturating_sub(*b)).collect(); + tracing::info!( + "pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}", + now.frame, + now.ms as f64 / 1e3 + ); + } + if (blips > 0 || steps.is_some_and(|s| s > 2)) && sets < 200 { + sets += 1; + save(before); + save(now); + save(after); + } + } + if crate::host::now_ms().saturating_sub(told) > 5000 { + told = crate::host::now_ms(); + for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) { + tracing::info!( + "pop watch, since the start, VICTORY_KEEP_SHOWN {} in its A/B phases: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped", + n, + s.frames, + s.blip_frames, + s.blips, + s.still, + s.steps + ); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn picture(color: u8) -> Vec { + vec![color; WIDE * HIGH * 3] + } + + fn patch(p: &mut [u8], bx: usize, by: usize, color: u8) { + for y in by * BLOCK..(by + 1) * BLOCK { + let at = (y * WIDE + bx * BLOCK) * 3; + p[at..at + BLOCK * 3].fill(color); + } + } + + #[test] + fn one_frame_otherwise_is_a_blip_and_a_lasting_change_a_step() { + let (a, mut b) = (picture(100), picture(100)); + patch(&mut b, 3, 4, 0); + let quiet = vec![0.0; (WIDE / BLOCK) * (HIGH / BLOCK)]; + assert_eq!(judge(&a, &b, &a, &quiet), (1, Some(0))); + assert_eq!(judge(&a, &b, &b, &quiet), (0, Some(1))); + assert_eq!(judge(&a, &a, &a, &quiet), (0, Some(0))); + // All of it changes: a cut, no step. + assert_eq!(judge(&a, &picture(0), &picture(0), &quiet), (0, None)); + // What moved just before is no step either. + assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0))); + } + + #[test] + fn times_are_read_and_pictures_made_small() { + assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]); + assert!(parse("x").is_empty()); + let rows: Vec = [1u8, 2, 3, 255].repeat(1280 * 720); + let out = small(&rows, 1280, 720, 1280 * 4, true); + assert_eq!((out.len(), &out[..3]), (WIDE * HIGH * 3, &[3u8, 2, 1][..])); + } +} From 350c686481113bae78dd0cbf608da5b7a897856a Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 10:50:14 -0600 Subject: [PATCH 02/31] First uploads of textures picked by index run on a copy queue of their own, their slots show them when they have (VICTORY_UPLOAD_AHEAD=1; off); blips found while the camera moves Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 4 +- crates/victory-gpu/src/descriptor/host.rs | 83 ++++- crates/victory-gpu/src/draw.rs | 24 +- crates/victory-gpu/src/popwatch.rs | 133 ++++++- crates/victory-gpu/src/resource.rs | 11 + crates/victory-gpu/src/texture.rs | 3 + crates/victory-gpu/src/texture/ahead.rs | 417 ++++++++++++++++++++++ 7 files changed, 654 insertions(+), 21 deletions(-) create mode 100644 crates/victory-gpu/src/texture/ahead.rs diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 6585bfa..16ba712 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -497,8 +497,8 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { } /// Runs `f` with the host heap of the title's largest view heap, if there is -/// one (reports: nothing is waited for). -#[cfg(all(windows, feature = "diagnostics"))] +/// one (nothing is waited for). +#[cfg(windows)] pub(crate) fn with_view_heap(f: impl FnOnce(&host::HostHeap) -> T) -> Option { let heaps = SHADER_HEAPS.try_read().ok()?; let host = heaps diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 47e7d5c..b1e8f00 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -326,6 +326,13 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option> = Mutex::new(Vec::new()); +/// Makes the slots whose new texture's upload has run +/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at +/// something else: the next texture pass does. +pub(crate) fn flip_now() { + let _ = super::with_view_heap(HostHeap::texture_slots_flip); +} + /// Since the start: slots made from their new view after its upload had run, /// and those the title had written again by then. pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; @@ -1986,19 +1993,27 @@ impl HostHeap { /// `handle` views, or something else: until then it shows the neutral /// texture ([`show_after`]). pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { + if self.show_later(index, handle) { + self.flip(list, index, handle, Some(crate::frame::current())); + } + } + + /// What slot `index` shows until the texture the record at `handle` views + /// is shown. False: it shows it, or there is none. + fn show_later(&self, index: u32, handle: u64) -> bool { use std::sync::atomic::Ordering::Relaxed; let key = record_key(handle); let view = view_at(key as u32, (key >> 32) as u32); let (true, Some(view)) = (key != 0, view) else { - return; + return false; }; { let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); let Some(&shown) = made.get(index as usize) else { - return; + return false; }; if shown == key { - return; + return false; } // (As `mirror`.) for stale in self.note_buffer(index, Some(&view), true) { @@ -2023,7 +2038,21 @@ impl HostHeap { self.keep(index, kept); } } - self.flip(list, index, handle, Some(crate::frame::current())); + true + } + + /// [`HostHeap::texture_slot_show_after`] of a texture whose upload `job` + /// makes: shown when that has run. + pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64) { + if !self.show_later(index, handle) { + return; + } + let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + let late = Some(crate::frame::current()); + job.then(move || { + let flip = Flip { after: 0, heap, index, handle, key, late }; + FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); + }); } /// [`HostHeap::mirror`] of a slot whose table a draw read: a texture made @@ -2037,6 +2066,7 @@ impl HostHeap { && let Some(View::Shader(resource, _)) = placed_texture(&view).or(Some(view)) && crate::resource::buffer_bytes(resource as crate::object::This).is_none() && crate::resource::host_resource(resource as crate::object::This).is_some_and(crate::pool::fresh) + && !crate::texture::ahead::there(resource as crate::object::This) { return self.texture_slot_show_after(list, index, handle); } @@ -2101,8 +2131,14 @@ impl HostHeap { #[cfg(feature = "diagnostics")] note_before(f.index, *shown, if f.late.is_some() { "shown after its upload" } else { "flip" }); self.put(f.index); + #[cfg(feature = "diagnostics")] + let was = *shown; *shown = f.key; self.keep(f.index, kept); + #[cfg(feature = "diagnostics")] + if f.late.is_some() && was != 0 { + same_bytes(was, f.key); + } if let Some(since) = f.late { let frames = crate::frame::current().saturating_sub(since); let n = LATE[0].fetch_add(1, Relaxed) + 1; @@ -4085,6 +4121,45 @@ fn rewritten(kin: Kin, kept: bool) { } } +/// Diagnostics: whether a texture that a slot showed until its new one came +/// holds the new one's bytes (the title moved it), by the bytes their host +/// copies were filled from: equal, different, not known. +#[cfg(feature = "diagnostics")] +fn same_bytes(old: u64, new: u64) { + use std::sync::atomic::Ordering::Relaxed; + static SEEN: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + let view = |key: u64| view_at(key as u32, (key >> 32) as u32); + let (Some(old), Some(new)) = (view(old), view(new)) else { + return; + }; + let held = |view: &View| { + let View::Placed(false, resource, desc) = view else { + return None; + }; + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + crate::resource::texture_held(crate::resource::texture_at_made(address, resource)?) + }; + let class = match kin(&old, &new) { + Kin::Moved => 0, + Kin::Same | Kin::None => return, + _ => 3, + }; + let which = match (held(&old), held(&new)) { + (Some(a), Some(b)) if a == b => 0, + (Some(a), Some(b)) if a.0 == b.0 => 1, + _ => 2, + }; + SEEN[class + which].fetch_add(1, Relaxed); + let n: u64 = SEEN.iter().map(|n| n.load(Relaxed)).sum(); + if n.is_multiple_of(1000) { + let seen: Vec = SEEN.iter().map(|n| n.load(Relaxed)).collect(); + tracing::info!( + "slots that went on showing another texture until the new one came, since the start: of one of the same kind elsewhere {} had the new one's bytes, {} others, {} not known; of others {}, {}, {}", + seen[0], seen[1], seen[2], seen[3], seen[4], seen[5] + ); + } +} + /// For `crate::popwatch`, since the start: slots made null as they were /// written with another texture, such that kept the old one, slots given the /// neutral texture, slots made null as their memory was another's. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9889269..a123ba8 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2380,7 +2380,7 @@ impl State { let _ = host.mirror(index, handle, true); } // Its bytes are in, or on the way there in a list before. - if late && texture.is_some_and(crate::pool::fresh) { + if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) { if let Some(handle) = heap.handle(index) { host.texture_slot_show_after(list, index, handle); } @@ -2398,7 +2398,27 @@ impl State { } continue; } - if let Some(view) = &view { + // The first upload of a texture no list has used: on a queue of + // its own, and the slot shows it as soon as that has run. + let ahead = if late && !tabled && texture.is_some_and(crate::pool::fresh) { + crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)) + } else { + None + }; + if let Some(ahead) = &ahead { + use crate::texture::ahead::Taken; + let (Taken::New(job) | Taken::Known(job)) = ahead; + if let Some(handle) = heap.handle(index) { + host.texture_slot_show_ahead(job, index, handle); + } + if let Taken::New(job) = ahead { + crate::texture::ahead::send(job); + } + } + let late = late && ahead.is_none(); + if let Some(view) = &view + && ahead.is_none() + { // (What was found mapped of it a moment ago is not asked // again, unless the host copy may need more.) crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX))); diff --git a/crates/victory-gpu/src/popwatch.rs b/crates/victory-gpu/src/popwatch.rs index fbba71e..4e4410f 100644 --- a/crates/victory-gpu/src/popwatch.rs +++ b/crates/victory-gpu/src/popwatch.rs @@ -5,7 +5,10 @@ //! - blips: blocks that one frame shows otherwise than the frames before and //! after it, which agree (a texture black, grey or another one for a frame); //! - steps: blocks that change from one frame to the next and stay so, while -//! most of the picture does not move. +//! most of the picture does not move; +//! - lone blocks: blocks found in neither neighbour, wherever the camera may +//! have moved them, while the neighbours' blocks there are found in each +//! other (a blip while the camera moves). //! //! `VICTORY_POP_FOLDER=`: the three pictures around a frame with //! blips (at most 200 times) are saved there, 640 wide; with @@ -66,11 +69,89 @@ struct Job { flown: u64, ms: u64, causes: [u64; 4], - phase: Option, + phase: usize, } /// Read-back buffers not in use. static FREE: Mutex> = Mutex::new(Vec::new()); +/// How far a block is looked for in a neighbour's picture, in pixels of half +/// the small picture's size, and the side of a block there. +const REACH: i32 = 14; +const HALF_BLOCK: usize = BLOCK / 2; + +/// A small picture at half its size, as brightness and two colour differences. +fn half(rgb: &[u8]) -> Vec<[i16; 3]> { + let (w, h) = (WIDE / 2, HIGH / 2); + let mut out = Vec::with_capacity(w * h); + for y in 0..h { + for x in 0..w { + let mut s = [0i16; 3]; + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let at = ((y * 2 + dy) * WIDE + x * 2 + dx) * 3; + for (s, v) in s.iter_mut().zip(&rgb[at..at + 3]) { + *s += i16::from(*v); + } + } + out.push(s.map(|s| s / 4)); + } + } + out +} + +/// Per block of `a`: how much it differs from the place in `b` that is most +/// like it, as [`differ`] says it. +fn moved(a: &[[i16; 3]], b: &[[i16; 3]]) -> Vec { + let (w, h) = (WIDE / 2, HIGH / 2); + let (across, down) = (WIDE / BLOCK, HIGH / BLOCK); + let mut out = vec![f32::MAX; across * down]; + for (n, best) in out.iter_mut().enumerate() { + let (bx, by) = (n % across * HALF_BLOCK, n / across * HALF_BLOCK); + let mut least = u32::MAX; + for dy in -REACH..=REACH { + let y0 = by as i32 + dy; + if y0 < 0 || y0 as usize + HALF_BLOCK > h { + continue; + } + for dx in -REACH..=REACH { + let x0 = bx as i32 + dx; + if x0 < 0 || x0 as usize + HALF_BLOCK > w { + continue; + } + let mut sum = 0u32; + for row in 0..HALF_BLOCK { + let ra = &a[(by + row) * w + bx..][..HALF_BLOCK]; + let rb = &b[(y0 as usize + row) * w + x0 as usize..][..HALF_BLOCK]; + sum += ra + .iter() + .zip(rb) + .map(|(p, q)| (0..3).map(|i| p[i].abs_diff(q[i])).max().unwrap_or(0) as u32) + .sum::(); + if sum >= least { + break; + } + } + least = least.min(sum); + } + } + *best = least as f32 / (HALF_BLOCK * HALF_BLOCK) as f32; + } + out +} + +/// Blocks of `now` found in neither neighbour, where `before` is found in +/// `after`. +fn lone(before: &[[i16; 3]], now: &[[i16; 3]], after: &[[i16; 3]]) -> Vec { + let (one, two) = (moved(now, before), moved(now, after)); + let both = moved(before, after); + // A cut on either side is none. + if one.iter().filter(|&&d| d > CHANGED).count() * 4 > one.len() + || two.iter().filter(|&&d| d > CHANGED).count() * 4 > two.len() + { + return Vec::new(); + } + (0..one.len()).filter(|&n| one[n] > CHANGED && two[n] > CHANGED && both[n] < CHANGED / 2.0).collect() +} + /// Frames on their way. static WAITING: AtomicU64 = AtomicU64::new(0); @@ -118,7 +199,8 @@ pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) { flown, ms: crate::host::now_ms(), causes: crate::descriptor::host::pop_causes(), - phase: crate::ab::pick("VICTORY_KEEP_SHOWN"), + phase: usize::from(crate::ab::pick("VICTORY_KEEP_SHOWN").unwrap_or(false)) + + 2 * usize::from(crate::ab::pick("VICTORY_UPLOAD_AHEAD").unwrap_or(false)), }; let _ = to.send(job); } @@ -131,14 +213,17 @@ struct Seen { blip_frames: u64, steps: u64, still: u64, + lone: u64, + lone_frames: u64, } struct Picture { frame: u64, ms: u64, causes: [u64; 4], - phase: Option, + phase: usize, rgb: Vec, + half: Vec<[i16; 3]>, /// Per block: how much it differs from the frame before. changed: Vec, saved: bool, @@ -228,7 +313,7 @@ fn save(p: &mut Picture) { fn watch(from: &mpsc::Receiver) { let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1"); let mut last: VecDeque = VecDeque::new(); - let mut seen: [Seen; 2] = Default::default(); + let mut seen: [Seen; 4] = Default::default(); let mut told = crate::host::now_ms(); let mut sets = 0; while let Ok(job) = from.recv() { @@ -257,7 +342,8 @@ fn watch(from: &mpsc::Receiver) { } let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default(); let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase); - last.push_back(Picture { frame, ms, causes, phase, rgb, changed, saved: false }); + let half = half(&rgb); + last.push_back(Picture { frame, ms, causes, phase, rgb, half, changed, saved: false }); if all && let Some(p) = last.back_mut() { save(p); } @@ -266,21 +352,24 @@ fn watch(from: &mpsc::Receiver) { } if let [first, before, now, after] = last.make_contiguous() { let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed); - let side = &mut seen[usize::from(now.phase.unwrap_or(false))]; + let side = &mut seen[now.phase]; side.frames += 1; side.blips += blips as u64; side.blip_frames += u64::from(blips > 0); side.still += u64::from(steps.is_some()); side.steps += steps.unwrap_or(0) as u64; - if blips > 0 || steps.is_some_and(|s| s > 0) { + let lone = lone(&before.half, &now.half, &after.half); + side.lone += lone.len() as u64; + side.lone_frames += u64::from(!lone.is_empty()); + if blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 0) { let since: Vec = now.causes.iter().zip(&first.causes).map(|(a, b)| a.saturating_sub(*b)).collect(); tracing::info!( - "pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}", + "pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps, lone blocks {lone:?}; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}", now.frame, now.ms as f64 / 1e3 ); } - if (blips > 0 || steps.is_some_and(|s| s > 2)) && sets < 200 { + if (blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 2)) && sets < 200 { sets += 1; save(before); save(now); @@ -291,13 +380,16 @@ fn watch(from: &mpsc::Receiver) { told = crate::host::now_ms(); for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) { tracing::info!( - "pop watch, since the start, VICTORY_KEEP_SHOWN {} in its A/B phases: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped", - n, + "pop watch, since the start, A/B VICTORY_KEEP_SHOWN {} VICTORY_UPLOAD_AHEAD {}: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped, lone blocks in {} frames ({} blocks)", + n & 1, + n >> 1, s.frames, s.blip_frames, s.blips, s.still, - s.steps + s.steps, + s.lone_frames, + s.lone ); } } @@ -333,6 +425,21 @@ mod tests { assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0))); } + #[test] + fn a_block_one_frame_alone_shows_is_found_while_the_camera_moves() { + // A picture of noise, moved by 6 pixels a frame. + let at = |shift: usize| -> Vec { + (0..HIGH) + .flat_map(|y| (0..WIDE).map(move |x| ((x + shift) / 8 * 37 + y / 8 * 91) as u8)) + .flat_map(|v| [v, v.wrapping_mul(3), 255 - v]) + .collect() + }; + let (a, mut b, c) = (at(0), at(8), at(16)); + assert!(lone(&half(&a), &half(&b), &half(&c)).is_empty()); + patch(&mut b, 20, 10, 128); + assert_eq!(lone(&half(&a), &half(&b), &half(&c)), vec![10 * (WIDE / BLOCK) + 20]); + } + #[test] fn times_are_read_and_pictures_made_small() { assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index faff1ac..416f3a4 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1177,6 +1177,8 @@ pub(crate) struct HostTexture { pub(crate) grown: std::sync::atomic::AtomicBool, /// What the last submitted upload put in it. pub(crate) holds: std::sync::Arc, + /// Who makes its first upload (`crate::texture::ahead`). + pub(crate) ahead: std::sync::atomic::AtomicU8, /// The texture's flags (asked once: the runtime takes 100 ns to say, and /// every texture of every draw is asked about). flags: u32, @@ -2295,6 +2297,7 @@ impl HostTexture { serial: SERIAL.fetch_add(1, Relaxed) + 1, grown: Default::default(), holds: Default::default(), + ahead: crate::texture::ahead::fresh(), flags, } } @@ -2319,6 +2322,7 @@ impl HostTexture { serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1, grown: Default::default(), holds: Default::default(), + ahead: crate::texture::ahead::fresh(), flags, } } @@ -2968,6 +2972,13 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option { Some(*found as This) } +/// From which level on the title texture's host copy was filled, and from +/// which bytes (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_held(resource: This) -> Option<(u32, crate::texture::Digest)> { + *made_copy(resource)?.holds.lock().unwrap_or_else(|e| e.into_inner()) +} + /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 365d024..1fbc585 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -15,6 +15,8 @@ //! (directly indexed views are not known per draw); plane 0 is uploaded //! (every mip and array slice), depth and stencil planes are not. +pub(crate) mod ahead; + use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -745,6 +747,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { return; }; let texture = ©.texture; + ahead::listed(©); let Some(staging) = staging(resource, ©, first) else { return; }; diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs new file mode 100644 index 0000000..4474435 --- /dev/null +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -0,0 +1,417 @@ +//! First uploads of textures picked by index on a copy queue of their own +//! (`VICTORY_UPLOAD_AHEAD`): read, detiled and copied by threads of ours as +//! soon as the texture pass has made them, and the slots that wait for them +//! shown when the copy has run. Recorded into the pass's list, as every other +//! upload is, the copy ran with the frame that needs it, so a slot that shows +//! its texture only after its upload ([`crate::descriptor::host::show_after`]) +//! was black or grey in that frame, and in the next. +//! +//! Only a texture that no list has used is taken: made in the last second, +//! in the common state, and never asked for an upload before +//! ([`crate::resource::HostTexture::ahead`]). It stays in the common state +//! (a copy queue's copies leave it there), from which the card's shaders read +//! it as any texture. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +use super::Staging; +use crate::object::This; +use crate::resource::HostTexture; + +/// [`HostTexture::ahead`]: no upload was asked for yet; one is on its way +/// here; it has run; one was recorded into a list. +pub(crate) const NONE: u8 = 0; +const PENDING: u8 = 1; +const DONE: u8 = 2; +pub(crate) const LISTED: u8 = 3; + +/// Bytes of title memory on their way at most: past it uploads go into the +/// lists, as before. +const MOST: u64 = 96 << 20; +/// Bytes and textures of one submission at most. +const BATCH: (u64, usize) = (16 << 20, 64); + +/// Whether it is on (`VICTORY_UPLOAD_AHEAD`; off). +pub(crate) fn on() -> bool { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_UPLOAD_AHEAD") { + return on; + } + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_AHEAD").is_some_and(|v| v != "0")) +} + +/// An upload on its way. +pub(crate) struct Job { + staging: Arc, + copy: Arc, + asked: std::time::Instant, + /// What to do when it has run; `None`: it has. + then: Mutex>>>, +} + +impl Job { + /// Calls `f` when the copy has run: now if it has. + pub(crate) fn then(&self, f: impl FnOnce() + Send + 'static) { + let mut then = self.then.lock().unwrap_or_else(|e| e.into_inner()); + match then.as_mut() { + Some(then) => then.push(Box::new(f)), + None => { + drop(then); + f(); + } + } + } +} + +/// What a texture asked for here gets. +pub(crate) enum Taken { + /// A job of its own, to be [`send`] once what follows it is added. + New(Arc), + /// One already on its way, or that has run. + Known(Arc), +} + +static QUEUE: (Mutex>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new()); +/// Those on their way, by host copy ([`HostTexture::serial`]). +static ON_THEIR_WAY: Mutex)>> = Mutex::new(Vec::new()); +static LANDED: Condvar = Condvar::new(); +static BYTES: AtomicU64 = AtomicU64::new(0); +/// Since the start: uploads, bytes, microseconds from the asking until the +/// copy had run, the longest; askings turned down; waits of lists. +static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// Takes the first upload of `resource`'s levels from `first` on, `there` of +/// whose bytes are mapped (`u64::MAX`: not known). `None`: the list's. +pub(crate) fn take(resource: This, first: u32, there: u64) -> Option { + if on() { claim(resource, first, there) } else { None } +} + +fn claim(resource: This, first: u32, there: u64) -> Option { + workers()?; + let turned_down = || { + STATS[4].fetch_add(1, Relaxed); + None + }; + let copy = crate::resource::host_copy(resource)?; + if copy.ahead.load(Relaxed) == PENDING { + let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone())); + } + if BYTES.load(Relaxed) >= MOST + || copy.flags() & 0x7 != 0 + || copy.state.load(Relaxed) != 0 + || copy.grown.load(Relaxed) + || copy.tiled.is_some() + || copy.holds.lock().unwrap_or_else(|e| e.into_inner()).is_some() + || !crate::pool::fresh(©.texture) + || super::host_wrote(resource as usize) + || crate::resource::alias_of(resource).is_some() + { + return turned_down(); + } + if copy.ahead.compare_exchange(NONE, PENDING, Relaxed, Relaxed).is_err() { + return turned_down(); + } + super::PICKING.set(Some(there)); + let staging = super::staging(resource, ©, first); + super::PICKING.set(None); + let Some(staging) = staging.filter(|s| { + !s.on_demand && s.first == s.level0 && !s.uploaded.load(Relaxed) && s.once.load(Relaxed) + }) else { + copy.ahead.store(LISTED, Relaxed); + return turned_down(); + }; + if super::no_wait() && super::fill_unlocked() { + staging.expected.store(if there == u64::MAX { super::mapped_bytes(staging.memory, staging.read) } else { there }, Relaxed); + } + let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) }); + BYTES.fetch_add(job.staging.read as u64, Relaxed); + ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone())); + Some(Taken::New(job)) +} + +/// Sends a job of [`take`] on its way. +pub(crate) fn send(job: &Arc) { + QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()).push_back(job.clone()); + QUEUE.1.notify_one(); +} + +/// A list is about to record an upload into `copy`: one on its way here runs +/// first, and no other is taken after it. +pub(crate) fn listed(copy: &HostTexture) { + if copy.ahead.compare_exchange(NONE, LISTED, Relaxed, Relaxed) != Err(PENDING) { + return; + } + STATS[5].fetch_add(1, Relaxed); + let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + let started = std::time::Instant::now(); + while way.iter().any(|(serial, _)| *serial == copy.serial) && started.elapsed().as_millis() < 1000 { + way = LANDED.wait_timeout(way, std::time::Duration::from_millis(50)).unwrap_or_else(|e| e.into_inner()).0; + } +} + +/// The copy queue and its threads, made on first use. +fn workers() -> Option<&'static ID3D12CommandQueue> { + /// Free-threaded. + struct Queue(ID3D12CommandQueue); + // SAFETY: a command queue is free-threaded. + unsafe impl Send for Queue {} + // SAFETY: as above. + unsafe impl Sync for Queue {} + static WORKERS: OnceLock> = OnceLock::new(); + WORKERS + .get_or_init(|| { + let host = crate::host::host()?; + // SAFETY: plain object creation. + let queue: ID3D12CommandQueue = unsafe { + host.device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + }) + .ok()? + }; + for n in 0..2 { + let worker = Worker::new(&host.device, queue.clone()).ok()?; + std::thread::Builder::new().name(format!("uploads ahead {n}")).spawn(move || worker.work()).ok()?; + } + Some(Queue(queue)) + }) + .as_ref() + .map(|q| &q.0) +} + +struct Worker { + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, +} + +// SAFETY: a worker's objects are its thread's own; the queue is free-threaded. +unsafe impl Send for Worker {} + +impl Worker { + fn new(device: &ID3D12Device, queue: ID3D12CommandQueue) -> windows::core::Result { + // SAFETY: plain object creation. + unsafe { + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + list.Close()?; + Ok(Worker { queue, allocator, list, fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)? }) + } + } + + fn work(self) { + let mut value = 0; + loop { + let mut jobs = Vec::new(); + { + let mut queue = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()); + while queue.is_empty() { + queue = QUEUE.1.wait(queue).unwrap_or_else(|e| e.into_inner()); + } + let mut bytes = 0; + while bytes < BATCH.0 && jobs.len() < BATCH.1 + && let Some(job) = queue.pop_front() + { + bytes += job.staging.read as u64; + jobs.push(job); + } + } + value += 1; + if let Err(e) = self.copy(&jobs, value) { + tracing::warn!(error = %e, "uploads ahead did not run"); + } + finish(jobs); + } + } + + fn copy(&self, jobs: &[Arc], value: u64) -> windows::core::Result<()> { + for job in jobs { + job.staging.refresh(); + } + // SAFETY: this worker's allocator and list, whose last submission has + // run; the jobs hold what the list names until after the wait. + unsafe { + self.allocator.Reset()?; + self.list.Reset(&self.allocator, None)?; + for job in jobs { + job.record(&self.list); + } + self.list.Close()?; + self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); + self.queue.Signal(&self.fence, value)?; + // (Without an event: this waits.) + self.fence.SetEventOnCompletion(value, windows::Win32::Foundation::HANDLE::default())?; + } + Ok(()) + } +} + +impl Job { + /// # Safety + /// `list` is an open copy list, and the job lives until it has run. + unsafe fn record(&self, list: &ID3D12GraphicsCommandList) { + let (s, texture) = (&self.staging, &self.copy.texture); + for (i, footprint) in s.footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s.first - s.level0 + i as u32 }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&s.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: s.base + footprint.Offset, ..*footprint }, + }, + }; + // SAFETY: the caller's. + unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + } +} + +/// The jobs' copies have run. +fn finish(jobs: Vec>) { + for job in &jobs { + job.staging.uploaded.store(true, Relaxed); + job.staging.dirty.store(false, Relaxed); + job.staging.note_held(); + job.copy.ahead.store(DONE, Relaxed); + BYTES.fetch_sub(job.staging.read as u64, Relaxed); + } + { + let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial)); + LANDED.notify_all(); + } + for job in &jobs { + let us = job.asked.elapsed().as_micros() as u64; + let n = STATS[0].fetch_add(1, Relaxed) + 1; + let bytes = STATS[1].fetch_add(job.staging.read as u64, Relaxed) + job.staging.read as u64; + let all = STATS[2].fetch_add(us, Relaxed) + us; + let most = STATS[3].fetch_max(us, Relaxed).max(us); + if n == 1 || n.is_multiple_of(5000) { + tracing::info!( + "textures uploaded ahead of the lists (VICTORY_UPLOAD_AHEAD=1), since the start: {n}, {} MB, {:.1} ms from the asking until they were there, the longest {:.0}; {} turned down, {} waited for by lists", + bytes >> 20, + all as f64 / n as f64 / 1e3, + most as f64 / 1e3, + STATS[4].load(Relaxed), + STATS[5].load(Relaxed) + ); + } + let then = job.then.lock().unwrap_or_else(|e| e.into_inner()).take(); + for f in then.into_iter().flatten() { + f(); + } + } + crate::descriptor::host::flip_now(); +} + +/// Whether `resource`'s host copy was filled here: no list still brings what +/// it shows. +pub(crate) fn there(resource: This) -> bool { + crate::resource::made_copy(resource).is_some_and(|copy| copy.ahead.load(Relaxed) == DONE) +} + +/// The state of [`HostTexture::ahead`] of a new host copy. +pub(crate) fn fresh() -> AtomicU8 { + AtomicU8::new(NONE) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The texels of a placed texture arrive by the copy queue, all levels of + /// them, and what waits for them is called then; a second asking finds the + /// first on its way, and a later one is the list's. + #[test] + fn a_placed_texture_is_filled_ahead_of_the_lists() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + let Some(host) = crate::host::host() else { return }; + // 256x256 BC7, nine levels. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::(); + // SAFETY: as above. + unsafe { (0..whole).for_each(|i| at.add(i).write((i * 13 + i / 509) as u8)) }; + let texture = crate::resource::texture_at(at as u64, &desc).unwrap(); + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture).unwrap(); + if !crate::pool::fresh(©.texture) { + return; + } + assert!(!there(texture)); + let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") }; + let (told, heard) = std::sync::mpsc::channel(); + let also = told.clone(); + let Some(Taken::Known(same)) = claim(texture, 0, u64::MAX) else { panic!("not known") }; + assert!(Arc::ptr_eq(&job, &same)); + job.then(move || told.send(1).unwrap()); + same.then(move || also.send(2).unwrap()); + send(&job); + let wait = std::time::Duration::from_secs(20); + assert_eq!((heard.recv_timeout(wait), heard.recv_timeout(wait)), (Ok(1), Ok(2))); + assert!(there(texture) && claim(texture, 0, u64::MAX).is_none()); + // Level 0 as the card has it, and as the layout says. + let layout = crate::resource::texture_memory(texture) + .and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone())) + .unwrap(); + let (pitch, rows) = (1024usize, 64usize); + let mut expected = vec![0u8; pitch * rows]; + // SAFETY: the memory above. + let tiled = unsafe { std::slice::from_raw_parts(at, whole) }; + layout.detile(tiled, 0, 0, &mut expected, pitch, pitch * rows).unwrap(); + let back = host.read_back_buffer((pitch * rows) as u64).unwrap(); + let list = host.new_list().unwrap(); + list.close(); + list.reset(); + let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98), + Width: 256, + Height: 256, + Depth: 1, + RowPitch: pitch as u32, + }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&back) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(©.texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + // SAFETY: an open list, live resources; the mapping spans the buffer. + unsafe { + list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None); + list.close(); + host.execute(&[&list]); + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let seen = std::slice::from_raw_parts(data.cast::(), pitch * rows); + assert!(seen == expected.as_slice(), "level 0's blocks"); + back.Unmap(0, None); + } + } +} From 9a6c829d6818a0ca0f1029d417e1e5eef6714eae Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 10:50:14 -0600 Subject: [PATCH 03/31] Shaders: normalized buffer codes give the nearest float, cube gradients take DXIL's base-2 logarithm, d16 data of integer views keeps its bits, unordered views of vertex programs are declared - VIctory da82e444: the host's division was a step off for some codes, and a material index cut from one was the code below. - DexNom/VIctory 921d8d3b (its cube part, with its test): the level was taken from a natural logarithm DXIL does not have, 1.44 times too high; the instruction's least level was lost. - VIctory 4243a96a, for buffers a program picks from the heap. - VIctory a1a2077a. Every shader is translated anew. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 30 ++- .../victory-shader/src/emit/cube_lod_tests.rs | 139 ++++++++++ crates/victory-shader/src/emit/diff_tests.rs | 2 +- crates/victory-shader/src/emit/host.rs | 26 +- .../src/emit/intersect_tests.rs | 12 +- crates/victory-shader/src/emit/lower.rs | 244 ++++++++++++++++-- crates/victory-shader/src/emit/mod.rs | 4 +- crates/victory-shader/src/emit/shader.rs | 20 ++ crates/victory-shader/src/emit/valu_tests.rs | 60 +++++ 9 files changed, 501 insertions(+), 36 deletions(-) create mode 100644 crates/victory-shader/src/emit/cube_lod_tests.rs diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b1e8f00..12ade75 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1005,6 +1005,17 @@ fn view_stride(view: &View) -> Option { }) } +/// What else the table of strides says of a typed buffer view of an integer +/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view. +fn view_kind(view: &View) -> u32 { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + match view_elements(view) { + Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER, + Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED, + _ => 0, + } +} + /// A buffer view's structure stride, whether it is raw, and its format; /// `None` if `view` is not a buffer view. fn view_elements(view: &View) -> Option<(u32, bool, u32)> { @@ -2366,12 +2377,13 @@ impl HostHeap { } } let stride = view.and_then(view_stride); + let kind = view.map_or(0, view_kind); if let Some((_, _, data)) = &self.strides && index < victory_shader::emit::SLOT_STRIDES_COUNT { // SAFETY: inside the mapping; shaders read it while we write (a // dword, either value is one the slot had). - unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) }; + unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) }; } let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); let was = if stride.is_some() { @@ -4580,6 +4592,22 @@ mod tests { assert!(!same_placed_texture(&low, &View::Shader(0, None))); } + /// Typed buffer views of integer formats are marked in the table of + /// strides; float, normalized, raw and structured ones are not. + #[test] + fn integer_typed_buffer_views_are_marked_in_the_table_of_strides() { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + // Format, dimension (buffer), first element, count, stride, counter, flags. + let uav = |format, stride, flags| View::Unordered(0, 0, Some([format, 1, 0, 0, 64, stride, 0, 0, flags, 0])); + assert_eq!(view_kind(&uav(12, 0, 0)), VIEW_INTEGER, "R16G16B16A16_UINT"); + assert_eq!(view_kind(&uav(59, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R16_SINT"); + assert_eq!(view_kind(&uav(10, 0, 0)), 0, "R16G16B16A16_FLOAT"); + assert_eq!(view_kind(&uav(58, 0, 0)), 0, "R16_SNORM"); + assert_eq!(view_kind(&uav(39, 0, 1)), 0, "raw"); + assert_eq!(view_kind(&uav(0, 16, 0)), 0, "structured"); + assert_eq!(view_stride(&uav(12, 0, 0)), Some(8)); + } + /// What may stand for a texture that is not there yet: one of its kind in /// another place or size; another one only if asked; nothing a shader /// cannot read in its place. diff --git a/crates/victory-shader/src/emit/cube_lod_tests.rs b/crates/victory-shader/src/emit/cube_lod_tests.rs new file mode 100644 index 0000000..96c79a3 --- /dev/null +++ b/crates/victory-shader/src/emit/cube_lod_tests.rs @@ -0,0 +1,139 @@ +//! Cube samples with gradients select their level by the footprint (after +//! DexNom/VIctory 921d8d3b). + +use super::host::{Dispatch, Host, Root, View}; +use super::intersect_tests::build_compute_shader; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use windows::Win32::Graphics::Direct3D12::*; + +/// The level is the red channel on all six faces so every sample returns +/// its selected mip directly (including the fraction with trilinear filtering). +#[test] +fn guest_cube_gradient_selects_mip_by_footprint() { + const SIZE: usize = 64; + const MIPS: u16 = 7; + let mut words = vec![ + 0xBE81_0380, + 0xBE83_0380, // s1, s3 = 0 (upper halves of the tables) + 0xF40C_0400, + 0xFA00_0000, // cube SRV to s[16:23] from s[0:1] + 0xF408_0300, + 0xFA00_0020, // raw output UAV to s[12:15] from s[0:1]+32 + 0xF408_0601, + 0xFA00_0000, // sampler to s[24:27] from s[2:3] + 0x7E1E_0280, // v15 = 0 for output byte offsets + ]; + let cases = [ + // image_sample_d: successive XY footprints (in texels). + (0x22, 1.0, 0.0, 0.0), + (0x22, 2.0, 0.0, 1.0), + (0x22, 16.0, 0.0, 4.0), + (0x22, 0.000001, 0.0, 0.0), + (0x22, 0.0, 0.0, 0.0), + // image_sample_d_cl: an instruction-specified minimum level. + (0x23, 1.0, 3.0, 3.0), + (0x23, 16.0, 2.0, 4.0), + (0x23, 0.0, 2.0, 2.0), + // image_sample_l and image_sample_lz: the level is given directly. + (0x24, 0.0, 2.0, 2.0), + (0x27, 0.0, 0.0, 0.0), + ]; + for (i, &(op, footprint, lod, _)) in cases.iter().enumerate() { + let delta = footprint / SIZE as f32; + let mut addr = Vec::new(); + if op == 0x22 || op == 0x23 { + addr.extend([delta, 0.0, 0.0, delta]); // derivatives along the face + } + addr.extend([1.5f32, 1.5, 0.0]); // positive X face, center + if op == 0x23 || op == 0x24 { + addr.push(lod); + } + for (reg, value) in addr.iter().enumerate() { + words.extend([0x7E00_02FF | ((reg as u32) << 17), value.to_bits()]); + } + // MIMG, CUBE, dmask:R, v0... inputs, SRV s16, sampler s24, result v10. + words.extend([0xF000_0118 | (op << 18), 0x00C4_0A00]); + // buffer_store_dword v10, v15, s[12:15], 0 offen offset:i*4 + words.extend([0xE070_1000 | (i as u32 * 4), 0x8003_0A0F]); + } + words.push(0xBF81_0000); // s_endpgm + let table = |slot, user_data| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot, + }; + let range = |kind, at, words, slot, user_data| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: at, + lower_bound: 0, + stride: 0, + dwords: words, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 16, + layout: vec![table(0, 0), table(1, 2)], + used: vec![ + range(ResourceType::Srv, 0, 8, 0, 0), + range(ResourceType::Uav, 8, 4, 0, 0), + range(ResourceType::Sampler, 0, 4, 1, 2), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 3 << 1, + threads: [1, 1, 1], + }), + code: words.into_iter().flat_map(u32::to_le_bytes).collect(), + }; + let (shader, _) = build_compute_shader(&native).unwrap(); + let texels: Vec<_> = (0..6) + .flat_map(|_| { + (0..MIPS).flat_map(|mip| std::iter::repeat_n([f32::from(mip); 4], (SIZE >> mip).pow(2))) + }) + .collect(); + let sampler = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxLOD: f32::MAX, + MaxAnisotropy: 1, + ..Default::default() + }; + for (name, warp) in [("WARP", true), ("hardware", false)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {name} device; skipped"); + continue; + }; + let (root, pso) = host.compute_pipeline(&shader).unwrap(); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![( + 0, + Root::Constants(vec![0; shader.user_data_dwords() as usize]), + )], + views: &[ + View::Cube(SIZE as u32, MIPS, &texels), + View::RawUav(cases.len() as u32), + ], + samplers: &[sampler], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let levels: Vec<_> = out[0].iter().copied().map(f32::from_bits).collect(); + let expected = cases.map(|(_, _, _, mip)| mip); + assert_eq!(levels.as_slice(), expected, "{name}"); + } +} diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index b43a0a7..21b4d03 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -1164,7 +1164,7 @@ fn translated_compute_matches_pc() { typed_view(DXGI_FORMAT_R8_UNORM, 1), typed_view(DXGI_FORMAT_R16_FLOAT, 2), typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4), - View::Cube(4, &cube_texels), + View::Cube(4, 1, &cube_texels), ]) .collect(); let root_cbv = floats(64, -0.125); diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 4bb533f..9196f51 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -994,8 +994,8 @@ fn transition( pub enum View<'a> { /// An RGBA32F texture SRV (width, height, texels). Texture(u32, u32, &'a [[f32; 4]]), - /// An RGBA32F cube SRV (face size, texels of faces +x -x +y -y +z -z). - Cube(u32, &'a [[f32; 4]]), + /// An RGBA32F cube SRV (face size, mip count, texels in D3D subresource order). + Cube(u32, u16, &'a [[f32; 4]]), /// A raw buffer UAV of this many dwords, zeroed. RawUav(u32), /// An RGBA32F texture UAV (width, height), zeroed. @@ -1170,20 +1170,23 @@ impl Host { at.ptr += i * view_size; match *v { View::Texture(..) | View::Cube(..) => { - let (w, h, texels, faces) = match *v { - View::Texture(w, h, t) => (w, h, t, 1), - View::Cube(n, t) => (n, n, t, 6), + let (w, h, mut texels, faces, mips) = match *v { + View::Texture(w, h, t) => (w, h, t, 1, 1), + View::Cube(n, mips, t) => (n, n, t, 6, mips), _ => unreachable!(), }; let mut desc = texture(w, h, D3D12_RESOURCE_FLAG_NONE); desc.DepthOrArraySize = faces as u16; + desc.MipLevels = mips; let tex = make( D3D12_HEAP_TYPE_DEFAULT, &desc, D3D12_RESOURCE_STATE_COPY_DEST, )?; - let pitch = (w as usize * 16).next_multiple_of(256); - for face in 0..faces as usize { + for sub in 0..u32::from(mips) * faces { + let mip = sub % u32::from(mips); + let (w, h) = ((w >> mip).max(1), (h >> mip).max(1)); + let pitch = (w as usize * 16).next_multiple_of(256); let upload = make( D3D12_HEAP_TYPE_UPLOAD, &buffer((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE), @@ -1191,9 +1194,10 @@ impl Host { )?; let mut p = std::ptr::null_mut(); upload.Map(0, None, Some(&mut p)).map_err(err)?; - let texels = &texels[face * (w * h) as usize..]; + let (level, rest) = texels.split_at((w * h) as usize); + texels = rest; for y in 0..h as usize { - let row = &texels[y * w as usize..(y + 1) * w as usize]; + let row = &level[y * w as usize..(y + 1) * w as usize]; std::ptr::copy_nonoverlapping( row.as_ptr().cast::(), p.cast::().add(y * pitch), @@ -1202,7 +1206,7 @@ impl Host { } upload.Unmap(0, None); let mut at_face = subresource(&tex); - at_face.Anonymous.SubresourceIndex = face as u32; + at_face.Anonymous.SubresourceIndex = sub; list.CopyTextureRegion( &at_face, 0, @@ -1224,7 +1228,7 @@ impl Host { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { TextureCube: D3D12_TEXCUBE_SRV { - MipLevels: 1, + MipLevels: u32::from(mips), ..Default::default() }, }, diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs index 684a08e..f2eddab 100644 --- a/crates/victory-shader/src/emit/intersect_tests.rs +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -162,13 +162,19 @@ fn build( wide: bool, descriptor: Descriptor, ) -> Result<(HostShader, resource::Resources), ShaderError> { - let native = native(&program(wide, descriptor)); + build_compute_shader(&native(&program(wide, descriptor))) +} + +/// `native`, a compute program, translated (the tests' own way: no container). +pub(super) fn build_compute_shader( + native: &NativeProgram, +) -> Result<(HostShader, resource::Resources), ShaderError> { let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); let st = structure::structure(&p).expect("structure"); let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native).expect("io::raise"); + let io = io::raise(&p, native).expect("io::raise"); let lowered = lower::lower(&lower::Parts { - native: &native, + native, p: &p, st: &st, io: &io, diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d8387d5..213f80d 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -6594,10 +6594,7 @@ impl<'a> Lower<'a> { /// typed loads do (channels past the format's read 0, 0, 0, 1). // shortcut: the descriptor's channel swizzle is taken as the identity // (it is for raw views and the descriptors code builds), elements of 4 - // bytes or more as dword-aligned. Norm formats divide, which the AMD - // driver does 1 ULP off the hardware's correctly rounded conversion for - // some values; correct it with an integer check if a title compares - // converted values exactly. + // bytes or more as dword-aligned. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result, Why> { let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; let c = self.cur; @@ -6660,10 +6657,15 @@ impl<'a> Lower<'a> { // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00. let x = match numeric { Numeric::Unorm => { - let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); let top = (1u64 << w) - 1; - let max = self.s.m.f32((top as f32).to_bits()); - let q = self.s.m.bin(c, Bin::SDiv, f, max); + let q = if w <= 16 { + let q = self.norm_quotient(field, w); + self.as_float(q) + } else { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + let max = self.s.m.f32((top as f32).to_bits()); + self.s.m.bin(c, Bin::SDiv, f, max) + }; let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits())); let at_top = self.s.m.cmp(c, pred::EQ, field, high); let q = self.s.m.select(c, at_top, one, q); @@ -6671,10 +6673,23 @@ impl<'a> Lower<'a> { } Numeric::Snorm => { let s = signed(self); - let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); let top = (1u32 << (w - 1)) - 1; - let max = self.s.m.f32((top as f32).to_bits()); - let q = self.s.m.bin(c, Bin::SDiv, f, max); + let q = if w <= 17 { + // The magnitude's quotient, signed (codes at and + // below -top are -1.0 below). + let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000)); + let neg = self.s.m.cmp(c, pred::SLT, s, zero); + let minus = self.s.m.bin(c, Bin::Sub, zero, s); + let m = self.s.m.select(c, neg, minus, s); + let q = self.norm_quotient(m, w - 1); + let sign = self.s.m.select(c, neg, sign, zero); + let q = self.s.m.bin(c, Bin::Or, q, sign); + self.as_float(q) + } else { + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + let max = self.s.m.f32((top as f32).to_bits()); + self.s.m.bin(c, Bin::SDiv, f, max) + }; // The lowest value is -1.0 too, as is the one above it. let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits())); let at_top = self.s.m.cmp(c, pred::SGE, s, high); @@ -6724,6 +6739,144 @@ impl<'a> Lower<'a> { Ok(out) } + /// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes + /// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for + /// a normalized code. The host's division is not exact (the RX 6700 XT + /// returns 8-bit codes one ulp high and some 16-bit codes one ulp low), + /// and titles truncate `x * d` back to the code (a material index in a + /// vertex colour's alpha), which a quotient one ulp low turns into the + /// code below. + /// + /// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K = + /// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1: + /// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d` + /// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when + /// its highest dropped bit is set, and the result is that integer (at + /// most 2^24, so its conversion is exact on any host) scaled by a power + /// of two; `Q` itself when it fits, the quotient's further bits then + /// lying below half an ulp. That holds for every code of every width but + /// 11 and 12 (checked for all codes of widths 2 to 16), which take + /// [`Self::exact_norm`]. The host's conversion of a larger integer is + /// not relied on: WARP rounds those above 2^31 otherwise. + fn norm_quotient(&mut self, a: V, w: u32) -> V { + if matches!(w, 11 | 12) { + return self.exact_norm(a, w); + } + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, kv) = (k(self, 1), k(self, kk)); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + if r != 1 { + let (rv, dv) = (k(self, r), k(self, d)); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + } + // The bits to drop (1 to 8) from the exponent of `q >> 8`, which + // converts exactly (fewer than 25 bits); none when `q` fits. + let k8 = k(self, 8); + let top = self.s.m.bin(c, Bin::LShr, q, k8); + let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32); + let top = self.as_int(top); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::LShr, top, k23); + let bias = k(self, 127 + 15); + let shift = self.s.m.bin(c, Bin::Sub, e, bias); + let (zero, b24) = (k(self, 0), k(self, 1 << 24)); + let fits = self.s.m.cmp(c, pred::IULT, q, b24); + let shift = self.s.m.select(c, fits, zero, shift); + // Rounded up when the highest dropped bit is set: `a / d` is never + // exact, so a dropped half is more than half, never a tie. + let up = self.s.m.bin(c, Bin::Shl, q, one); + let up = self.s.m.bin(c, Bin::LShr, up, shift); + let up = self.s.m.bin(c, Bin::And, up, one); + let m = self.s.m.bin(c, Bin::LShr, q, shift); + let m = self.s.m.bin(c, Bin::Add, m, up); + // At most 2^24: exact as a float, and so its scale by 2^(shift - 32). + let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32); + let b95 = k(self, 127 - 32); + let scale = self.s.m.bin(c, Bin::Add, shift, b95); + let scale = self.s.m.bin(c, Bin::Shl, scale, k23); + let scale = self.as_float(scale); + let f = self.s.m.bin(c, Bin::Mul, f, scale); + self.as_int(f) + } + + /// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q` + /// as there, 8 more bits when that leaves fewer than 25 (codes of wide + /// formats near 0), then rounded to 24 bits to nearest even with the + /// remainder as sticky bit, and assembled as float bits. + fn exact_norm(&mut self, a: V, w: u32) -> V { + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8)); + let kv = k(self, kk); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + let mut rem = a; + if r != 1 { + let rv = k(self, r); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + rem = self.s.m.bin(c, Bin::URem, t, dv); + } + // The exponent's bias less the 32 (or 40) fraction bits of `q`; the + // shift below is added. + let mut bias = k(self, 127 + 23 - 32); + if kk < 1 << 24 { + // Fewer than 25 bits for the smallest codes: 8 more. + let t = self.s.m.bin(c, Bin::Shl, rem, k8); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + let rest = self.s.m.bin(c, Bin::URem, t, dv); + let wide = self.s.m.bin(c, Bin::Shl, q, k8); + let wide = self.s.m.bin(c, Bin::Or, wide, more); + let limit = k(self, 1 << 24); + let small = self.s.m.cmp(c, pred::IULT, q, limit); + q = self.s.m.select(c, small, wide, q); + rem = self.s.m.select(c, small, rest, rem); + let b40 = k(self, 127 + 23 - 40); + bias = self.s.m.select(c, small, b40, bias); + } + // Bits to drop: the bit length less 24, 1 to 8. + let mut shift = one; + for bit in 25..32 { + let at = k(self, 1 << bit); + let ge = self.s.m.cmp(c, pred::IUGE, q, at); + let add = self.s.m.select(c, ge, one, zero); + shift = self.s.m.bin(c, Bin::Add, shift, add); + } + let mant = self.s.m.bin(c, Bin::LShr, q, shift); + let below = self.s.m.bin(c, Bin::Sub, shift, one); + let half = self.s.m.bin(c, Bin::LShr, q, below); + let half = self.s.m.bin(c, Bin::And, half, one); + let low = self.s.m.bin(c, Bin::Shl, one, below); + let low = self.s.m.bin(c, Bin::Sub, low, one); + let low = self.s.m.bin(c, Bin::And, q, low); + let rest = self.s.m.bin(c, Bin::Or, low, rem); + let sticky = self.s.m.cmp(c, pred::NE, rest, zero); + let odd = self.s.m.bin(c, Bin::And, mant, one); + let tie = self.s.m.select(c, sticky, one, odd); + let up = self.s.m.bin(c, Bin::And, half, tie); + let mant = self.s.m.bin(c, Bin::Add, mant, up); + // Rounding up to 2^24 moves to the next exponent. + let k24 = k(self, 24); + let carry = self.s.m.bin(c, Bin::LShr, mant, k24); + let mant = self.s.m.bin(c, Bin::LShr, mant, carry); + let e = self.s.m.bin(c, Bin::Add, bias, shift); + let e = self.s.m.bin(c, Bin::Add, e, carry); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::Shl, e, k23); + let fraction = k(self, 0x7F_FFFF); + let m = self.s.m.bin(c, Bin::And, mant, fraction); + let bits = self.s.m.bin(c, Bin::Or, e, m); + let is_zero = self.s.m.cmp(c, pred::EQ, a, zero); + self.s.m.select(c, is_zero, zero, bits) + } + /// Channels of buffer format `format`, as [`Self::format_load`] gives /// them, as d16 data: 16 bits each, two per dword, low half first (an /// odd last high half 0). Integer formats keep their low 16 bits; the @@ -7152,6 +7305,33 @@ impl<'a> Lower<'a> { /// `ResourceHeap`): read from the host's table by heap slot in the /// current block. fn slot_stride(&mut self, src: &Source) -> Result, Why> { + let word = self.slot_word(src)?; + Ok(word.map(|word| { + let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS); + self.s.m.bin(self.cur, Bin::And, word, bits) + })) + } + + /// Whether the typed buffer view `src` names is one of an integer format, + /// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the + /// program does not pick from the heap). + fn integer_view(&mut self, src: &Source) -> Result, Why> { + let Some(word) = self.slot_word(src)? else { + return Ok(None); + }; + let c = self.cur; + let zero = self.s.m.i32(0); + let [int, signed] = [super::shader::VIEW_INTEGER, super::shader::VIEW_SIGNED].map(|bit| { + let bit = self.s.m.i32(bit); + let x = self.s.m.bin(c, Bin::And, word, bit); + self.s.m.cmp(c, pred::NE, x, zero) + }); + Ok(Some((int, signed))) + } + + /// The host's word for the buffer view `src` names: its stride and + /// format kind ([`super::shader::SLOT_STRIDES`]). + fn slot_word(&mut self, src: &Source) -> Result, Why> { let Source::Loaded { load, first } = src else { return Ok(None); }; @@ -10938,11 +11118,14 @@ impl<'a> Lower<'a> { let width = self.s.m.extract(c, d, 0); let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32); let texels = self.s.m.bin(c, Bin::Mul, longer, width); - // log2 = natural logarithm / ln 2; a length of 0 gives + // DXIL's logarithm is the one to base 2 (it was taken for + // the natural one: every level came out 1.44 times too + // high; DexNom/VIctory 921d8d3b). A length of 0 gives // minus infinity, which the sampler clamps to level 0. - let ln = self.unary(23, texels); - let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits()); - let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2); + // SampleLevel takes no clamp: the instruction's least + // level is applied here. + let lod = self.unary(23, texels); + let lod = if has_cl { self.binary(35, lod, clamp) } else { lod }; args.extend(&os); args.push(lod); call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) @@ -11509,8 +11692,14 @@ impl<'a> Lower<'a> { let mut vals = self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; if d16 { - // shortcut: d16 data is taken as f16 (integer formats would - // keep 16 bits), widened for the 32-bit float store. + // d16 data is taken as f16, widened for the 32-bit float + // store; through a view of an integer format it is a 16-bit + // integer, zero- or sign-extended (VIctory 4243a96a: the face + // network keeps its halves in UINT views; its output was + // noise). shortcut: that is known of the views a program + // picks from the heap, not of those in its tables; and the + // handle stays a float one, whose bits the drivers pass. + let integer = if typed { self.integer_view(src)? } else { None }; let mut wide = Vec::new(); for k in 0..count { let mut x = vals[(k / 2) as usize]; @@ -11522,7 +11711,16 @@ impl<'a> Lower<'a> { let f = self .s .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); - wide.push(self.as_int(f)); + let mut w = self.as_int(f); + if let Some((int, signed)) = integer { + let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); + let zero_ext = self.s.m.bin(c, Bin::And, x, low); + let up = self.s.m.bin(c, Bin::Shl, x, k16); + let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16); + let n = self.s.m.select(c, signed, sign_ext, zero_ext); + w = self.s.m.select(c, int, n, w); + } + wide.push(w); } vals = wide; } @@ -11657,16 +11855,24 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; if d16 { - // Two f16 channels per VGPR (an odd last high half 0). + // Two f16 channels per VGPR (an odd last high half 0); the low + // 16 bits of an integer view's (see the stores above). + let integer = if typed { self.integer_view(src)? } else { None }; let k16 = self.s.m.i32(16); let i32t = self.s.t.i32; for k in 0..count.div_ceil(2) { let mut x = None; for ch in (2 * k..(2 * k + 2).min(count)).rev() { let f = self.s.m.extract(c, r, ch); - let h = self + let mut h = self .s .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + if let Some((int, _)) = integer { + let bits = self.as_int(f); + let low = self.s.m.i32(0xFFFF); + let low = self.s.m.bin(c, Bin::And, bits, low); + h = self.s.m.select(c, int, low, h); + } x = Some(match x { Some(hi) => { let hi = self.s.m.bin(c, Bin::Shl, hi, k16); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f98517d..b0ca117 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -83,6 +83,8 @@ mod bitcode; mod container; #[cfg(all(test, windows))] +mod cube_lod_tests; +#[cfg(all(test, windows))] mod diff_tests; #[cfg(all(test, windows))] mod intersect_tests; @@ -118,7 +120,7 @@ pub use lower::{host_settings, set_host_max_wave}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, - SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 264de50..1f6585f 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -24,6 +24,14 @@ pub const ROOT_CBV_SPACE: u32 = 1; /// root SRV also tells the host that the buffer views of the whole heap /// must be ready when it runs, not only those its tables name. pub const SLOT_STRIDES: u8 = 255; +/// The bits of a [`SLOT_STRIDES`] dword that hold the stride. +pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; +/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format +/// (`UINT` or `SINT`), whose 16-bit typed accesses (`_d16`) pass bits. +/// (After VIctory 4243a96a.) +pub const VIEW_INTEGER: u32 = 1 << 31; +/// With [`VIEW_INTEGER`]: a signed (`SINT`) format. +pub const VIEW_SIGNED: u32 = 1 << 30; /// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it. pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; @@ -93,6 +101,8 @@ pub(crate) mod flags { pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; + /// Unordered views in a vertex, geometry or mesh program. + pub const UAVS_EVERY_STAGE: u64 = 1 << 16; pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; pub const BARYCENTRICS: u64 = 1 << 22; @@ -557,6 +567,13 @@ impl Shader { } } } + // Unordered views outside pixel and compute programs (memory by + // address), as DXC counts them: ranges declared below, not views + // picked from the heap (VIctory a1a2077a). + let compute = self.threads.is_some() && self.mesh.is_none() && self.geometry.is_none(); + if !self.root_uavs.is_empty() && !self.pixel && !compute { + self.flags |= flags::UAVS_EVERY_STAGE; + } let mut resources = None; let mut bindings = Vec::new(); let i32c = |s: &mut Self, v: u32| { @@ -871,6 +888,9 @@ impl Shader { if self.flags & flags::DOUBLES != 0 { features |= 0x1; } + if self.flags & flags::UAVS_EVERY_STAGE != 0 { + features |= 0x4; + } if self.flags & flags::STENCIL_REF != 0 { features |= 0x200; } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index cd2806f..3aa9145 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -415,6 +415,66 @@ fn normalized_buffer_formats_load_their_ends_exactly() { } } +/// Codes of the normalized formats sampled below: every 8-bit code; for +/// 16 bits a stride, the RX 6700 XT's division misses (257, 261, ...) and +/// the ends. +fn normalized_codes(bits: u32) -> Vec { + if bits <= 10 { + return (0..1 << bits).collect(); + } + let edges = [1, 2, 3, 255, 256, 257, 261, 265, 269, 511, 512, 1000, 0x7FFF, 0x8000, 0x8001, 0xFFFE]; + (0..=0xFFFF).step_by(257).chain(edges).collect() +} + +/// Every normalized code loads as the float nearest its exact quotient, +/// as the console's buffer unit converts it, not as the host divides (the +/// RX 6700 XT gave 125 of the 8-bit codes one ulp high and 16-bit codes +/// such as 257 one ulp low): unsigned and signed, 8, 10 (the x channel of +/// 2_10_10_10) and 16 bits, the signed formats' two lowest codes -1.0. +#[test] +fn normalized_buffer_formats_load_correctly_rounded_quotients() { + let x = 0; + // (format, bits, signed): 8_UNORM, 16_UNORM, 8_SNORM, 16_SNORM, + // 2_10_10_10_UNORM and _SNORM. + for (format, bits, signed) in [(1u8, 8u32, false), (7, 16, false), (2, 8, true), (8, 16, true), (50, 10, false), (51, 10, true)] { + let shader = tbuffer_load_of_v1(x, format); + let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect(); + run_cases(&shader, &cases, |backend, _, [a, ..], got| { + let want = if signed { + let top = (1i32 << (bits - 1)) - 1; + let s = ((a << (32 - bits)) as i32) >> (32 - bits); + (s.max(-top) as f32 / top as f32).to_bits() + } else { + (a as f32 / ((1u32 << bits) - 1) as f32).to_bits() + }; + let sign = if signed { "signed" } else { "unsigned" }; + assert_eq!(got, want, "{backend}: {bits}-bit {sign} normalized {a:#x} loads as {got:#010x}, want {want:#010x}"); + }); + } +} + +/// A title truncates `x * (2^n - 1)` back to the code it stored (the +/// material index a mesh program reads from a vertex colour's alpha, as +/// `v_mul_legacy_f32` by 255.0 then `v_cvt_u32_f32`): every code comes back +/// as itself, on hardware and WARP, which a quotient one ulp low breaks. +#[test] +fn normalized_codes_truncate_back_to_themselves() { + let x = 0; + for (format, bits) in [(1u8, 8u32), (7, 16)] { + let scale = (((1u32 << bits) - 1) as f32).to_bits(); + let mut body = buffer_store_dword(1, 8, 0).to_vec(); + body.extend(mtbuf(x, 0, 8, format)); + // v_mul_legacy_f32 v0, literal, v0; v_cvt_u32_f32 v0, v0. + body.extend([0x07 << 25 | 0xFF, scale]); + body.push(vop1(0x07, 0, vgpr(0))); + let shader = build_valu_cs(&body); + let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect(); + run_cases(&shader, &cases, |backend, _, [a, ..], got| { + assert_eq!(got, a, "{backend}: {bits}-bit code {a} comes back as {got}"); + }); + } +} + #[test] fn packed_add_selects_halves_of_inline_constants() { // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. From 3315f29a75176f3d9db777114fb5f2de9c247322 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 10:52:47 -0600 Subject: [PATCH 04/31] The run's numbers on the picture (VICTORY_PANEL=1; off; F3 shows and hides it) White on black in the upper left corner of what is shown, twice a second, from the counters of the frame-rate line, memory and textures; our own 5x7 characters. Copied onto the swap chain's buffer out of a buffer in the card's memory: screenshots carry it, saved frames and the frame recorder do not. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/Cargo.toml | 2 +- crates/victory-gpu/src/copystat.rs | 9 +- crates/victory-gpu/src/draw.rs | 6 + crates/victory-gpu/src/host.rs | 16 + crates/victory-gpu/src/host/panel.rs | 486 ++++++++++++++++++++++++ crates/victory-gpu/src/pipeline.rs | 6 + crates/victory-gpu/src/replay/record.rs | 6 + 7 files changed, 529 insertions(+), 2 deletions(-) create mode 100644 crates/victory-gpu/src/host/panel.rs diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 858802a..16c7495 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -30,7 +30,7 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 484c90a..34c214d 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -161,6 +161,13 @@ pub(crate) fn add(c: C, n: u64) { COUNT[bank()].0[c as usize].fetch_add(n, Relaxed); } +/// The counter, all sets together, as it is now (it goes back to 0 with +/// [`log`]). +pub(crate) fn peek(c: C) -> u64 { + let i = c as usize; + COUNT.iter().map(|b| b.0[i].load(Relaxed)).sum() +} + /// Counter `i`, all sets together, from now on 0. fn taken(i: usize) -> u64 { COUNT.iter().map(|b| b.0[i].swap(0, Relaxed)).sum() @@ -491,7 +498,7 @@ mod own_tests { /// The process's memory in bytes: in physical memory, and committed /// (private bytes). -fn process_memory() -> (u64, u64) { +pub(crate) fn process_memory() -> (u64, u64) { use windows_sys::Win32::System::ProcessStatus::{ K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, }; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9889269..ccf8c8e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -452,6 +452,12 @@ pub(crate) fn take_frame() -> Vec { std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner())) } +/// The draws dropped since [`take_dropped`]. +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] +pub(crate) fn dropped_now() -> u64 { + DROPPED.load(Ordering::Relaxed) +} + /// Draws, mesh dispatches and dispatches recorded but not run on the host /// (no host pipeline) since the last call. pub(crate) fn take_dropped() -> u64 { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 507a79d..7702f90 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3467,6 +3467,8 @@ pub(crate) mod aside; pub(crate) mod awake; mod card_steps; pub(crate) mod indirects; +#[cfg(feature = "diagnostics")] +mod panel; mod place; mod send; pub(crate) use send::{goes_as_words, words_under}; @@ -7960,6 +7962,8 @@ struct Presenter { ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, + #[cfg(feature = "diagnostics")] + panel: panel::Panel, } /// The frame rate, shown in the window's caption every second and logged @@ -7989,6 +7993,12 @@ impl Meter { } } + /// Whether the next frame counted makes the frame-rate line. + #[cfg(feature = "diagnostics")] + fn line_due(&self) -> bool { + self.since.elapsed() >= std::time::Duration::from_secs(1) + } + /// Counts a presented frame. fn frame(&mut self, hwnd: HWND) { #[cfg(feature = "diagnostics")] @@ -8363,6 +8373,8 @@ impl Host { .flatten(); #[cfg(feature = "diagnostics")] let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + #[cfg(feature = "diagnostics")] + p.panel.draw(self, copy, &back, (width, height), format); #[cfg(not(feature = "diagnostics"))] let _ = frame; list.ResourceBarrier(&[ @@ -8390,6 +8402,8 @@ impl Host { let mut showing = crate::timeline::span("the host's Present"); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); showing.next("the frame meter"); + #[cfg(feature = "diagnostics")] + p.panel.frame(p.meter.line_due()); p.meter.frame(p.hwnd); showing.end(); #[cfg(feature = "diagnostics")] @@ -8442,6 +8456,8 @@ impl Host { ahead: Vec::new(), hwnd, meter: Meter::new(), + #[cfg(feature = "diagnostics")] + panel: panel::Panel::new(), }) } } diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs new file mode 100644 index 0000000..586d08f --- /dev/null +++ b/crates/victory-gpu/src/host/panel.rs @@ -0,0 +1,486 @@ +//! Diagnostics: the run's numbers on the picture (`VICTORY_PANEL=1`; off by +//! default; F3 shows and hides it while our window has the focus): white +//! text on a black box in the upper left corner of what is shown, so that a +//! screenshot carries them. Made again twice a second from the counters of +//! the frame-rate line, memory and textures; a frame itself only copies the +//! box out of a buffer in the card's memory. Copied onto the swap chain's +//! buffer, behind the title's picture: saved frames and the frame recorder +//! see the title's own. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_F3}; +use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; + +use super::{Host, HostList, transition}; + +/// How often the numbers change. +const EVERY: Duration = Duration::from_millis(500); + +/// A character's dots, and with the space beside and below it. +const GLYPH: (u32, u32) = (5, 7); +const CELL: (u32, u32) = (6, 9); +/// Characters in a line, lines, and the box's rim in dots. +const COLUMNS: u32 = 43; +const LINES: u32 = 14; +const RIM: u32 = 3; + +/// The texts are put into one of these in turn: the card reads the others, +/// at most half a second old. +const UPLOADS: usize = 4; + +fn asked() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_PANEL")) +} + +/// Whether it is shown now. +fn shown() -> &'static AtomicBool { + static SHOWN: OnceLock = OnceLock::new(); + SHOWN.get_or_init(|| AtomicBool::new(asked())) +} + +/// F3 was pressed since the last call, with one of our windows in front. +fn pressed() -> bool { + static DOWN: AtomicBool = AtomicBool::new(false); + // SAFETY: a plain query. + let down = unsafe { GetAsyncKeyState(i32::from(VK_F3)) } < 0; + if DOWN.swap(down, Ordering::Relaxed) || !down { + return false; + } + let mut process = 0; + // SAFETY: plain queries; room for the answer. + unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) }; + process == std::process::id() +} + +/// Seven rows of five dots, the leftmost the highest bit. +#[rustfmt::skip] +const fn glyph(c: u8) -> [u8; 7] { + match c { + b'0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110], + b'1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], + b'2' => [0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111], + b'3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110], + b'4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010], + b'5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110], + b'6' => [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110], + b'7' => [0b11111, 0b00001, 0b00010, 0b00010, 0b00100, 0b00100, 0b00100], + b'8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110], + b'9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100], + b'A' => [0b00100, 0b01010, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001], + b'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110], + b'C' => [0b01111, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b01111], + b'D' => [0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110], + b'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111], + b'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000], + b'G' => [0b01111, 0b10000, 0b10000, 0b10011, 0b10001, 0b10001, 0b01111], + b'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001], + b'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], + b'J' => [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100], + b'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001], + b'L' => [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111], + b'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001], + b'N' => [0b10001, 0b11001, 0b11001, 0b10101, 0b10011, 0b10011, 0b10001], + b'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110], + b'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000], + b'Q' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101], + b'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001], + b'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110], + b'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100], + b'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110], + b'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100], + b'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001], + b'X' => [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001], + b'Y' => [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100], + b'Z' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111], + b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100], + b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000], + b'-' => [0, 0, 0, 0b11111, 0, 0, 0], + b' ' => [0; 7], + _ => [0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111], + } +} + +/// The box's size in pixels, a dot being `scale` of them each way. +const fn size(scale: u32) -> (u32, u32) { + ((COLUMNS * CELL.0 + 2 * RIM) * scale, (LINES * CELL.1 + 2 * RIM) * scale) +} + +/// Pixels to a dot for a picture that high: a 720-line screenshot of it +/// shows one and a third. +fn scale(height: u32) -> u32 { + (height / 540).max(1) +} + +/// Whether a dot of the picture of `lines` is white. +fn lit(lines: &[String], x: u32, y: u32) -> bool { + let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else { + return false; + }; + if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= COLUMNS { + return false; + } + let Some(&c) = lines.get((y / CELL.1) as usize).and_then(|l| l.as_bytes().get((x / CELL.0) as usize)) else { + return false; + }; + (glyph(c.to_ascii_uppercase())[(y % CELL.1) as usize] >> (GLYPH.0 - 1 - x % CELL.0)) & 1 != 0 +} + +/// The bytes of a black and a white pixel of a swap chain's format. +fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> { + Some(match format { + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM => [&[0, 0, 0, 0xFF], &[0xFF; 4]], + DXGI_FORMAT_R10G10B10A2_UNORM => [&[0, 0, 0, 0xC0], &[0xFF; 4]], + // Halves of 0 and 1. + DXGI_FORMAT_R16G16B16A16_FLOAT => [ + &[0, 0, 0, 0, 0, 0, 0, 0x3C], + &[0, 0x3C, 0, 0x3C, 0, 0x3C, 0, 0x3C], + ], + _ => return None, + }) +} + +/// The box as rows of `pitch` bytes. +fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec { + let (width, height) = size(scale); + let bytes = colours[0].len(); + let mut out = vec![0; pitch * height as usize]; + for y in 0..height / scale { + let top = pitch * (y * scale) as usize; + for x in 0..width / scale { + let colour = colours[usize::from(lit(lines, x, y))]; + for i in 0..scale { + let at = top + (x * scale + i) as usize * bytes; + out[at..at + bytes].copy_from_slice(colour); + } + } + for i in 1..scale as usize { + out.copy_within(top..top + pitch, top + i * pitch); + } + } + out +} + +/// The counters read for it. They grow, and go back to 0 with the frame-rate +/// line (right behind a look of ours). +#[derive(Clone, Copy, Default)] +struct Counters([u64; COUNTERS]); + +const COUNTERS: usize = 16; + +impl Counters { + fn now() -> Counters { + use super::{CARD_CLOCK_US, COPY_BACK, PREPARING, SUBMISSION_US}; + use crate::copystat::{C, peek}; + let get = |a: &std::sync::atomic::AtomicU64| a.load(Ordering::Relaxed); + Counters([ + get(&SUBMISSION_US[0]), + get(&PREPARING[0]), + get(&PREPARING[1]), + get(&PREPARING[2]), + get(&PREPARING[3]), + get(©_BACK[0]), + get(©_BACK[1]), + get(&CARD_CLOCK_US[0]), + get(&CARD_CLOCK_US[1]), + get(&CARD_CLOCK_US[2]), + get(&crate::shadow::CARD_STATS[0]), + crate::draw::dropped_now(), + peek(C::RecordNs), + peek(C::RecordCalls), + peek(C::Submissions), + crate::draw::drawn(), + ]) + } + + /// What came since `before`, per frame. + fn since(self, before: Counters, frames: f64) -> [f64; COUNTERS] { + let mut out = [0.0; COUNTERS]; + for (i, out) in out.iter_mut().enumerate() { + let (was, is) = (before.0[i], self.0[i]); + *out = if is >= was { is - was } else { is } as f64 / frames; + } + out + } +} + +/// The text. `c`: [`Counters`] per frame, `ms` a frame's time, `worst` the +/// longest frame's. +fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, host: &Host) -> Vec { + use crate::draw::{ + HEAP_TEXTURE_BYTES, HEAP_TEXTURES, HEAP_TEXTURES_AWAY, HEAP_TEXTURES_FULL, HEAP_TEXTURES_WAITING, + }; + let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64; + let get = |a: &std::sync::atomic::AtomicU64| a.load(Ordering::Relaxed); + let (working, private) = crate::copystat::process_memory(); + let [budget, used, _, shared] = host.video_memory().unwrap_or_default(); + let (hits, misses) = crate::shader_cache::counts(); + let failed = get(&crate::pipeline::FAILED); + let idle = (c[7] / 1e3).min(ms); + vec![ + format!("FPS {:.1} FRAME {ms:.1} MS LONGEST {worst:.0}", 1e3 / ms.max(0.001)), + format!("DRAWS {:.0} DROPPED {:.1} SUBMITS {:.1}", c[15], c[11], c[14]), + format!("CPU PREP {:.1} MS COPY {:.1} TEXTURES {:.1}", c[0] / 1e3, c[1] / 1e3, c[3] / 1e3), + format!("RECORDING {:.0} MS IN {:.0} CALLS", c[12] / 1e6, c[13]), + format!("GPU BUSY {:.1} MS IDLE {idle:.1} BEHIND US {:.1}", ms - idle, c[8] / 1e3), + format!("WAIT FOR GPU {:.1} MS COPY BACK {:.1} MS", c[9] / 1e3, c[5] / 1e3), + format!("MB UP {:.1} ON CARD {:.1} TEX {:.1} BACK {:.1}", c[2] / 1e6, c[10] / 1e6, c[4] / 1e6, c[6] / 1e6), + format!("RAM PRIVATE {:.1} GB IN MEMORY {:.1} GB", gb(private), gb(working)), + format!("VRAM {:.1}/{:.1} GB SHARED {:.1} GB", gb(used), gb(budget), gb(shared)), + format!( + "TEXTURES {} {:.1} GB WAITING {}", + get(&HEAP_TEXTURES), + gb(get(&HEAP_TEXTURE_BYTES)), + get(&HEAP_TEXTURES_WAITING) + ), + format!( + "UNMAPPED {} NO ROOM {} VIEWS {}", + get(&HEAP_TEXTURES_AWAY), + get(&HEAP_TEXTURES_FULL), + get(&crate::descriptor::host::REFUSED_VIEWS) + ), + format!("SHADERS CACHED {hits} NEW {misses} FAILED {failed}"), + format!("PIPELINES QUEUED {}", crate::pipeline::making()), + format!("FRAME NO {}", crate::queue::presented()), + ] +} + +/// The buffers of a box that size and format. +struct Buffers { + format: DXGI_FORMAT, + scale: u32, + pitch: u32, + uploads: Vec<(ID3D12Resource, *mut u8)>, + card: ID3D12Resource, + /// The upload written last. + turn: usize, + /// It is not in the card's buffer yet. + fresh: bool, +} + +// SAFETY: free-threaded resources, and memory only written under the presenter's lock. +unsafe impl Send for Buffers {} + +impl Buffers { + fn new(host: &Host, format: DXGI_FORMAT, scale: u32) -> Option { + let (width, height) = size(scale); + let pitch = (width * colours(format)?[0].len() as u32).next_multiple_of(256); + let bytes = u64::from(pitch) * u64::from(height); + let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::>>()?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut card: Option = None; + // SAFETY: plain creation of a buffer. + unsafe { + host.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card) + .ok()?; + } + Some(Buffers { format, scale, pitch, uploads, card: card?, turn: 0, fresh: false }) + } + + fn write(&mut self, lines: &[String]) { + let Some(colours) = colours(self.format) else { return }; + let picture = painted(lines, self.scale, colours, self.pitch as usize); + self.turn = (self.turn + 1) % UPLOADS; + // SAFETY: a mapped upload buffer of the picture's size, which the card read a second or more ago. + unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) }; + self.fresh = true; + } +} + +/// The panel of a presenter. +pub(super) struct Panel { + since: Instant, + frames: u32, + last: Instant, + worst: f64, + before: Counters, + lines: Vec, + changed: bool, + buffers: Option, + failed: bool, +} + +impl Panel { + pub(super) fn new() -> Panel { + let now = Instant::now(); + Panel { + since: now, + frames: 0, + last: now, + worst: 0.0, + before: Counters::default(), + lines: Vec::new(), + changed: false, + buffers: None, + failed: false, + } + } + + /// A frame was presented; `line`: the counters go back to 0 right behind + /// this call. + pub(super) fn frame(&mut self, line: bool) { + if pressed() { + shown().fetch_xor(true, Ordering::Relaxed); + } + let now = Instant::now(); + self.frames += 1; + self.worst = self.worst.max((now - self.last).as_secs_f64() * 1e3); + self.last = now; + let elapsed = now - self.since; + if elapsed < EVERY && !(line && elapsed * 2 >= EVERY) { + return; + } + let (frames, worst) = (f64::from(self.frames), self.worst); + (self.since, self.frames, self.worst) = (now, 0, 0.0); + if !shown().load(Ordering::Relaxed) { + return; + } + let Some(host) = super::host() else { return }; + let counters = Counters::now(); + let c = counters.since(self.before, frames); + self.before = counters; + self.lines = text(&c, elapsed.as_secs_f64() * 1e3 / frames, worst, host); + self.changed = true; + } + + /// Records the copy of the box onto `back`, a buffer of the swap chain of + /// that size and format in the state to be copied into. + pub(super) fn draw( + &mut self, + host: &Host, + list: &HostList, + back: &ID3D12Resource, + (width, height): (u32, u32), + format: DXGI_FORMAT, + ) { + if !shown().load(Ordering::Relaxed) || self.lines.is_empty() || self.failed { + return; + } + // Not the title's: the frame recorder leaves it out. + let _ours = crate::replay::record::unrecorded(); + let scale = scale(height); + if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { + // (What the card may still read stays: a picture's size changes once or twice in a run.) + std::mem::forget(self.buffers.take()); + self.buffers = Buffers::new(host, format, scale); + self.failed = self.buffers.is_none(); + self.changed = true; + } + let Some(buffers) = &mut self.buffers else { return }; + if std::mem::take(&mut self.changed) { + buffers.write(&self.lines); + } + let (w, h) = size(scale); + let list = &list.list; + // SAFETY: an open list and live resources; the box lies within both. + unsafe { + if std::mem::take(&mut buffers.fresh) { + list.CopyResource(&buffers.card, &buffers.uploads[buffers.turn].0); + list.ResourceBarrier(&[transition( + &buffers.card, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + } + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffers.card), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: format, + Width: w, + Height: h, + Depth: 1, + RowPitch: buffers.pitch, + }, + }, + }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(back), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let part = D3D12_BOX { + left: 0, + top: 0, + front: 0, + right: w.min(width), + bottom: h.min(height), + back: 1, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&part)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every character the lines use has its own picture, and no two look + /// alike. + #[test] + fn characters_differ() { + let used: Vec = (b'0'..=b'9').chain(b'A'..=b'Z').chain(*b"./- ").collect(); + for (i, a) in used.iter().enumerate() { + assert_ne!(glyph(*a), glyph(b'#'), "{} has a picture", *a as char); + assert!(glyph(*a).iter().all(|row| row >> GLYPH.0 == 0)); + for b in &used[i + 1..] { + assert_ne!(glyph(*a), glyph(*b), "{} {}", *a as char, *b as char); + } + } + } + + #[test] + fn a_box_is_painted() { + let lines = vec!["I".to_owned(), " i".to_owned()]; + for scale in [1, 2, 4] { + let (width, height) = size(scale); + let pitch = (width * 4).next_multiple_of(256) as usize; + let colours = colours(DXGI_FORMAT_R10G10B10A2_UNORM).unwrap(); + let picture = painted(&lines, scale, colours, pitch); + assert_eq!(picture.len(), pitch * height as usize); + let at = |x: u32, y: u32| &picture[y as usize * pitch + x as usize * 4..][..4]; + // The rim is black, the first letter's top row lit in its middle. + assert_eq!(at(0, 0), colours[0]); + assert_eq!(at((RIM + 2) * scale, RIM * scale), colours[1]); + assert_eq!(at((RIM + 2) * scale + scale - 1, RIM * scale + scale - 1), colours[1]); + assert_eq!(at(RIM * scale, RIM * scale), colours[0]); + // Small letters are shown as capitals, a line and a cell on. + assert_eq!(at((RIM + CELL.0 + 2) * scale, (RIM + CELL.1) * scale), colours[1]); + // Nothing past a line's end. + assert_eq!(at((RIM + CELL.0 * 2 + 2) * scale, (RIM + CELL.1) * scale), colours[0]); + } + } + + #[test] + fn counters_that_went_back_to_nothing_count_from_there() { + let (mut a, mut b) = (Counters::default(), Counters::default()); + (a.0[0], b.0[0]) = (10, 30); + (a.0[1], b.0[1]) = (50, 20); + let c = b.since(a, 10.0); + assert_eq!((c[0], c[1]), (2.0, 2.0)); + } +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 7a00633..0945b4c 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -78,6 +78,9 @@ static SHADERS: Mutex>>> = Mutex::new(None) /// kept and the bytes of their host code. None of them is ever let go. static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +/// Shaders that did not translate. +pub(crate) static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// What the shader table and the pipeline library keep in memory: /// containers and their bytes, translations and their bytes, the bytes of /// the library's file (kept whole while the library lives) and what its @@ -158,6 +161,9 @@ impl Shader { KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed); } + if done.is_err() { + FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } match &done { Ok(t) => tracing::info!( stage = self.stage, diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index 232f7b7..70a1fa4 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -393,6 +393,12 @@ impl Drop for Ours { } } +/// While what this returns lives, this thread's D3D12 calls are not +/// recorded. +pub(crate) fn unrecorded() -> impl Drop { + Ours::new() +} + fn ours() -> bool { OURS.with(|o| o.get() > 0) } From e77a7d9fd90fb35ba6513ac3c97e7298656f02fb Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 10:55:15 -0600 Subject: [PATCH 05/31] Ranges of memory that changed under texture views are joined before they are looked up (DexNom/VIctory 921d8d3b) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 26 ++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 12ade75..84c6a94 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -722,6 +722,20 @@ pub(crate) fn remapped(at: usize, len: usize) { ranges.push((start, end)); } +/// Ranges of memory, those that touch made one (DexNom/VIctory 921d8d3b: +/// several threads map and write, some 5,000 ranges a frame, the same +/// textures' over and over, and each was looked up). +fn join(ranges: &mut Vec<(u64, u64)>) { + ranges.sort_unstable(); + ranges.dedup_by(|next, last| { + if next.0 > last.1 { + return false; + } + last.1 = last.1.max(next.1); + true + }); +} + /// Frames for which a slot a draw read through a table counts as a table's /// slot ([`HostHeap::tabled`]). const TABLED_FRAMES: u64 = 240; @@ -1711,10 +1725,11 @@ impl HostHeap { pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize { use std::sync::atomic::Ordering::Relaxed; self.texture_slots_page_written(frame); - let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); + let mut ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); if ranges.is_empty() { return 0; } + join(&mut ranges); let mut slots: Vec = { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect() @@ -4592,6 +4607,15 @@ mod tests { assert!(!same_placed_texture(&low, &View::Shader(0, None))); } + #[test] + fn ranges_that_touch_are_one() { + let mut ranges = vec![(40, 50), (30, 40), (35, 40), (10, 20), (45, 60), (60, 61), (1, 1)]; + join(&mut ranges); + assert_eq!(ranges, [(1, 1), (10, 20), (30, 61)]); + join(&mut ranges); + assert_eq!(ranges.len(), 3); + } + /// Typed buffer views of integer formats are marked in the table of /// strides; float, normalized, raw and structured ones are not. #[test] From 30f46c92a974514ba0a90acc36c814c237c002bc Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:40 -0600 Subject: [PATCH 06/31] Structure builder: fences around its buffer atomics (VICTORY_BVH_FENCES=0: none) Its threads take turns through atomics; what one wrote before its atomic has to be seen by the one after it. The console's waits for writes are not in the translated code. After beloooo's 72e748ea (VIctory-Belobug-AMD). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shader_cache.rs | 1 + crates/victory-shader/src/emit/lower.rs | 20 ++++++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 8 ++++++++ 3 files changed, 29 insertions(+) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index d5cf03f..35b5446 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -73,6 +73,7 @@ fn build() -> [u8; 32] { "VICTORY_FIRST_HALF", "VICTORY_STRICT_JOINS", "VICTORY_MESH_OUTPUT_STRICT", + "VICTORY_BVH_FENCES", ] { bytes.extend_from_slice(name.as_bytes()); bytes.push(b'='); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index d8387d5..ecad742 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -5230,6 +5230,17 @@ impl<'a> Lower<'a> { let void = self.s.t.void; self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } + // The structure builder's threads take turns through atomics (a tree + // built from its leaves up): what one wrote before its atomic is + // seen by the thread that comes after it. The console's program + // waits for its writes there, and those waits are not in the code + // here (after beloooo's 72e748ea, VIctory-Belobug-AMD). + let ordered = (name.starts_with("buffer_atomic") || name.starts_with("global_atomic")) + && crate::spill::is_spilled(self.x.native) + && super::builder_fences(); + if ordered { + self.memory_fence(); + } let r = match &inst.fields { Fields::Sop { .. } => self.sop(inst), Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), @@ -5275,6 +5286,9 @@ impl<'a> Lower<'a> { Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i), Fields::Flat { .. } => Err("flat memory"), }; + if ordered && r.is_ok() { + self.memory_fence(); + } match r { Ok(()) => Ok(()), Err(why) if effect => Err(unsupported(offset, why)), @@ -5287,6 +5301,12 @@ impl<'a> Lower<'a> { } } + /// Writes to buffers made before are seen, by every group, before those made after. + fn memory_fence(&mut self) { + let (mode, void) = (self.s.m.i32(2), self.s.t.void); + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + /// The two host waves of a console wave meet (a group barrier with a shared-memory /// fence): LDS writes before are seen by reads after. fn lds_meeting(&mut self) { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index f98517d..b714dc6 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -180,6 +180,14 @@ pub fn group_sync() -> u8 { }) } +/// Whether buffer atomics of the ray-tracing structure builder stand between +/// two fences (`VICTORY_BVH_FENCES=0`: they do not). Part of the +/// translation: the shader cache keys on it. +pub fn builder_fences() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_FENCES").is_none_or(|v| v != "0")) +} + /// The clean-up passes that run over a translated program before it is /// written (`bitcode::opt`): a set of that module's pass bits. Every pass /// is exact, so the switch is for telling a translator fault from a From a50c7fdeb55eca4a27c70151b4154665c32e22e9 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:41 -0600 Subject: [PATCH 07/31] Replay: buffers in heaps opened from memory are made again (without the cross-adapter flag) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/replay/play.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index b823576..b157414 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -735,7 +735,11 @@ impl Player { let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64)); *m = (m.0 + 1, m.1 + r.desc.width); } - let desc = gpu::to_desc(&r.desc); + let mut desc = gpu::to_desc(&r.desc); + // (Heaps are made without what let others open them.) + if matches!(r.place, Place::Placed { .. }) { + desc.Flags &= !D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } let mut made: Option = None; let clear: Option = r.clear.map(|c| { // SAFETY: 20 bytes that were a clear value. From 2c20d7a6e31f8bcfa3d9d0b62942ee7df0a7edc2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:43 -0600 Subject: [PATCH 08/31] Structure builder: submissions that ask for structures' sizes are waited for (VICTORY_BVH_SIZES_WAIT=0: not); a packed structure is one node longer; VICTORY_BVH_TRACE The title reads a new structure's compacted size a frame or two after it asked, takes memory of that size and copies the structure there. It read the size the slot held before: the copies wrote over their neighbours (run light-11). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 2 +- crates/victory-gpu/src/host.rs | 3 + crates/victory-gpu/src/memory.rs | 159 ++++++++++++++++++++++++++++++- 3 files changed, 161 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9889269..c1bbae5 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1260,7 +1260,7 @@ impl State { addresses.push(self.view_address(compute, u.slot, u.dword)); } } - crate::memory::ready(list, heap, &addresses, &written, &constants, use_) + crate::memory::ready(list, heap, &addresses, &written, &constants, use_, t.threads) } /// The bound heap holding `handle`. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 507a79d..58c8171 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4906,6 +4906,7 @@ impl Host { return; }; let told = !sent.writes.is_empty(); + let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); let most = { let mut line = line(); let Line { line: items, written, lists: flying, target, .. } = &mut *line; @@ -4928,6 +4929,8 @@ impl Host { RELAY_MOVED.notify_one(); if told && !late_writes() { self.settle(&mut submitted, WHY_WRITES); + } else if sizes { + self.settle(&mut submitted, WHY_READ); } else if most && relay_exact() { // Until there are fewer, not until there are none. relay_wait(WHY_MOST, |line| line.lists < late_most()); diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 65a2cd7..441990a 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -181,6 +181,8 @@ struct Memory { stats: Stats, #[cfg(feature = "diagnostics")] dump: dump::Dump, + #[cfg(feature = "diagnostics")] + trace: trace::Trace, } /// Since the last report. @@ -254,6 +256,8 @@ impl Memory { stats: Stats::default(), #[cfg(feature = "diagnostics")] dump: Default::default(), + #[cfg(feature = "diagnostics")] + trace: Default::default(), }) } @@ -789,6 +793,49 @@ impl Memory { } } +/// A list with this key ([`HostList::used`]) asks the builder for sizes. +const SIZES: usize = usize::MAX - (9 << 33); + +/// Whether a submission that asks for the sizes of structures is waited for, +/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=0`: it is +/// not). +/// +/// The title asks for a new structure's compacted size (a program of one +/// thread stores it into a small buffer), reads it a frame or two later +/// without looking whether it is there, takes memory of that size and copies +/// the structure into it. With submissions that land up to two frames late it +/// read what the slot held before, some other structure's size, and the copy +/// wrote over its neighbours: of 230 such copies of run light-11, 99 were +/// asked for two frames earlier and landed in that frame, none of those with +/// the right size. +fn sizes_wait() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_none_or(|v| v != "0")) +} + +/// Whether a dispatch of the builder is its program of a structure's size: +/// one thread, the structure's address and what to store (1: the compacted +/// size) as constants, a small title buffer to store into. +fn asks_size(written: &[u64], constants: &[u32], threads: Option<[u32; 3]>) -> bool { + threads == Some([1, 1, 1]) + && matches!(*constants, [_, hi, 1..=3, ..] if (1..0x20).contains(&hi)) + && written.first().is_some_and(|&at| crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK)) +} + +/// Whether one of `lists` asks for sizes. +pub(crate) fn asked_sizes<'a>(lists: impl Iterator) -> bool { + let mut lists = lists; + let asked = sizes_wait() && lists.any(|l| l.used(SIZES)); + if asked { + static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() || n.is_multiple_of(100) { + tracing::info!(n, frame = crate::frame::current(), "submissions that ask for structures' sizes, waited for"); + } + } + asked +} + /// [`fill`] of a page stores by address do not reach. fn close(entry: *mut u32, n: usize, offset: u64) { fill(entry, n | MEMORY_READ_ONLY as usize, offset); @@ -809,7 +856,10 @@ fn fill(entry: *mut u32, n: usize, offset: u64) { fn packed_len(header: u64) -> Option { let (version, nodes) = (header as u32, header >> 32); let marks = version >> 16; - (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && nodes * 64 <= PACKED).then_some(nodes * 64) + // The header counts its nodes of 64 bytes without the last one: the + // builder's own program of a structure's size stores one more. + let len = (nodes + 1) * 64; + (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && len <= PACKED).then_some(len) } /// Puts what `title` holds into `ours` (what was last taken): the dwords that @@ -845,6 +895,7 @@ pub(crate) fn ready( written: &[u64], constants: &[u32], use_: Use, + threads: Option<[u32; 3]>, ) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { @@ -858,8 +909,17 @@ pub(crate) fn ready( m.take_faults(); m.look_again(); m.report(); + #[cfg(feature = "diagnostics")] + m.trace.look(frame); + } + #[cfg(feature = "diagnostics")] + if use_ != Use::Reads { + m.trace.dispatch(frame, list, addresses, written, constants, threads); } let builds = use_ != Use::Reads; + if builds && sizes_wait() && asks_size(written, constants, threads) { + list.first_use(SIZES); + } while builds && m.free.len() < SPARE && m.pages.len() + m.free.len() < MOST && m.another() {} m.stats.uses[usize::from(builds)] += 1; // Once per list and page named: the builder dispatches hundreds of times @@ -1004,6 +1064,101 @@ pub(crate) fn ready( }) } +/// `VICTORY_BVH_TRACE=1`: the sizes the builder is asked for (its program of +/// one thread that stores a structure's compacted size) and when title memory +/// has them, and the copies to a place of that size. +#[cfg(feature = "diagnostics")] +mod trace { + use super::*; + + #[derive(Default)] + pub(super) struct Trace { + /// Frame, where the size goes, the structure, what title memory had. + asked: Vec<(u64, u64, u64, u64)>, + /// By structure, what its size was when last seen to change. + sizes: HashMap, + said: u32, + } + + fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_TRACE").is_some_and(|v| v == "1")) + } + + fn value(at: u64) -> u64 { + let mut b = [0u8; 8]; + crate::host::copy_mapped(b.as_mut_ptr(), at as *const u8, 8, false); + u64::from_le_bytes(b) + } + + impl Trace { + fn say(&mut self, text: String) { + self.said += 1; + if self.said < 6000 { + tracing::info!("bvh trace: {text}"); + } + } + + pub(super) fn look(&mut self, frame: u64) { + if !on() { + return; + } + let mut gone = Vec::new(); + for i in 0..self.asked.len() { + let (then, at, structure, was) = self.asked[i]; + let now = value(at); + if now != was { + self.sizes.insert(structure, (now, frame)); + gone.push(i); + self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: {was:#x} -> {now:#x}")); + } else if frame > then + 60 { + gone.push(i); + self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: still {was:#x}")); + } + } + for i in gone.into_iter().rev() { + self.asked.swap_remove(i); + } + } + + pub(super) fn dispatch( + &mut self, + frame: u64, + list: &HostList, + addresses: &[u64], + written: &[u64], + constants: &[u32], + threads: Option<[u32; 3]>, + ) { + if !on() { + return; + } + let _ = addresses; + let list = std::ptr::from_ref(list) as usize & 0xFFFF_FFFF; + if threads == Some([1, 1, 1]) + && let [lo, hi, mode, ..] = *constants + && (1..=3).contains(&mode) + && hi < 0x20 + && let Some(&at) = written.first() + && crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK) + { + let structure = u64::from(lo) | u64::from(hi) << 32; + let was = value(at); + self.say(format!("frame {frame} list {list:x}: asks mode {mode} of {structure:#x} to {at:#x}, there {was:#x}")); + if mode == 1 { + self.asked.push((frame, at, structure, was)); + } + } else if threads == Some([32, 1, 1]) + && let [from, to] = *written + && [from, to].iter().all(|&a| a >= 1 << 32 && crate::shadow::in_buffer(a, 1).is_none()) + { + let known = self.sizes.get(&from).copied(); + self.say(format!("frame {frame} list {list:x}: copies {from:#x} to {to:#x} constants {:x?}, its size was {known:x?}", &constants[..constants.len().min(4)])); + } + } + } +} + /// `VICTORY_MEMORY_DUMP=`: when a file `go` appears there, the arenas /// as the card holds them are copied out and written (`arena-.bin`), with /// `pages.txt` (title page, arena, offset) and the structures the walking @@ -1132,7 +1287,7 @@ mod tests { #[test] fn a_packed_structure_is_known_by_its_header() { let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32; - assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1a * 64)); + assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1b * 64)); // Unpacked, a top level, another version, no size, too big. assert_eq!(packed_len(header(0x8002_0006, 0x9a1a)), None); assert_eq!(packed_len(header(0x0000_0006, 5)), None); From 82ca13473857d578f6febed48620f23075b16e88 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:09:43 -0600 Subject: [PATCH 09/31] A stand-in for the title's traced indirect light (VICTORY_AMBIENT, off): estimated from the light visible surfaces send out After beloooo's constant (VIctory-Belobug-AMD 06031237, 4f45ab88, cd9f78ce). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/ambient.rs | 477 +++++++++++++++++++++++++++++ crates/victory-gpu/src/draw.rs | 64 ++++ crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pipeline.rs | 5 + 4 files changed, 548 insertions(+) create mode 100644 crates/victory-gpu/src/ambient.rs diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs new file mode 100644 index 0000000..fb45f90 --- /dev/null +++ b/crates/victory-gpu/src/ambient.rs @@ -0,0 +1,477 @@ +//! A stand-in for the indirect light the title traces rays for. +//! +//! With the ray-tracing structure builder off (`crate::pipeline::builder_runs`) +//! the title's rays find nothing. Its program that resolves the diffuse light +//! of its screen probes (`CS_ScreenProbes_TemporalResolve_*`) then leaves the +//! sky's light outdoors, nothing indoors (walls are black where no lamp or +//! sun reaches) and, in blocks of the picture's tiles, what the probes' +//! memory held. Right after that program the light is raised to an estimate +//! and bounded by a multiple of it. +//! +//! That a stand-in can be put there, and in which of the program's images, +//! is beloooo's find (VIctory-Belobug-AMD, 06031237, 4f45ab88, cd9f78ce, +//! GPL-3.0-or-later), which puts a constant there, shaded in creases from the +//! scene's depth. The estimate here is worked out from the frame instead, so +//! it follows the hour, the room and its lamps by itself: the light the +//! visible surfaces send out (the title keeps it for its own screen traces: +//! `CS_CacheScreenSpaceRadiance`, the frame before) is averaged in 64x36 +//! cells, and every point gets the mean of the cells weighted by the share of +//! its surroundings they cover, as a directional value (first-order harmonics +//! at 160x90 points, taken between them by depth). +//! +//! What it assumes: what is not on screen sends out what is (with a slow +//! mean of the last seconds, so that turning into a dark corner is not black +//! at once). No occlusion but the creases'. +//! +//! `VICTORY_AMBIENT`: +//! - unset or `0`/`off`: the title's own output. +//! - a number: that share of the estimate (1: all of it). +//! - `constant:`: the constant, as beloooo's fork has it. +//! +//! `VICTORY_AMBIENT_SHADE=,` sets the creases. + +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::s; + +use crate::host::{HostList, host}; + +/// Programs of the title the stand-in follows. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Role { + /// Resolves the diffuse light. + Resolve, + /// Keeps the light visible surfaces send out. + Radiance, +} + +/// The program's part in this, by its name in the container. +pub(crate) fn role(container: &[u8]) -> Option { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if has(b"CS_ScreenProbes_TemporalResolve") { + Some(Role::Resolve) + } else if has(b"CS_CacheScreenSpaceRadiance") { + Some(Role::Radiance) + } else { + None + } +} + +/// Where the resolve writes the diffuse light (R9G9B9E5 as 32-bit integers) +/// and reads the scene's depth, and where the other writes the light of +/// visible surfaces: root parameter and place in its table, in dwords. +pub(crate) const LIGHT: (u8, u32) = (1, 176); +pub(crate) const DEPTH: (u8, u32) = (0, 464); +pub(crate) const RADIANCE: (u8, u32) = (1, 16); + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Set { + Off, + Estimate(f32), + Constant(f32), +} + +fn parse(set: &str) -> Set { + let set = set.trim(); + let number = |t: &str| t.trim().parse::().ok().filter(|v| v.is_finite() && *v > 0.0); + match set.strip_prefix("constant:") { + Some(level) => number(level).map_or(Set::Off, Set::Constant), + None => number(set).map_or(Set::Off, Set::Estimate), + } +} + +fn set() -> Set { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| parse(&std::env::var("VICTORY_AMBIENT").unwrap_or_default())) +} + +/// Whether the stand-in is on: set, and the title's rays find nothing. +pub(crate) fn on() -> bool { + set() != Set::Off && !crate::pipeline::builder_runs() +} + +/// Strength and radius of the creases' shade. +fn shade() -> [f32; 2] { + static SET: OnceLock<[f32; 2]> = OnceLock::new(); + *SET.get_or_init(|| { + let mut shade = [1.0, 0.6]; + let set = std::env::var("VICTORY_AMBIENT_SHADE").unwrap_or_default(); + for (to, v) in shade.iter_mut().zip(set.split(',')) { + if let Ok(v) = v.trim().parse() { + *to = v; + } + } + shade + }) +} + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=12, b0), DescriptorTable(SRV(t0)), DescriptorTable(UAV(u0)), UAV(u1), UAV(u2)" +#define CX 64 +#define CY 36 +#define CELLS (CX * CY) +#define PX 160 +#define PY 90 +cbuffer Set : register(b0) { + float level; float constant; float strength; float radius; + float near; float tan_y; uint width; uint height; + float follow; float most; float unused0; float unused1; +}; +Texture2D depth : register(t0); +// Cells: the light they send out (then, at CELLS, the slow mean), from +// CELLS + 1 on where they are. +RWStructuredBuffer cells : register(u1); +// Three a point: red, green and blue, each a mean and a direction. +RWStructuredBuffer points : register(u2); +static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); + +// The point seen at a texel, in metres from the eye (x right, y up, z away). +float3 seen(int2 p, float2 size) { + float d = depth.Load(int3(clamp(p, int2(0, 0), int2(size) - 1), 0)); + float z = min(near / max(d, 1e-7), 1000.0); + float2 ndc = (float2(p) + 0.5) / size * 2.0 - 1.0; + return float3(ndc.x * tan_y * size.x / size.y * z, -ndc.y * tan_y * z, z); +} + +#ifdef KEEP +RWTexture2D radiance : register(u0); +[RootSignature(RS)] +[numthreads(8, 4, 1)] +void keep(uint3 at : SV_DispatchThreadID) { + uint w, h; + radiance.GetDimensions(w, h); + float3 sum = 0; + for (uint y = 0; y < 5; y++) for (uint x = 0; x < 5; x++) { + uint2 p = uint2((float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(w, h) / float2(CX, CY)); + float3 c = max(radiance[p], 0.0); + c = any(isnan(c)) || any(isinf(c)) ? 0.0 : c; + // Lamps and glints count, but not for everything. + sum += c / max(1.0, dot(c, LUMA) / 20.0); + } + cells[at.y * CX + at.x] = float4(sum / 25.0, 1.0); +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void mean() { + float3 sum = 0; + for (uint i = 0; i < CELLS; i++) sum += cells[i].rgb; + float4 was = cells[CELLS]; + float3 now = sum / CELLS; + cells[CELLS] = float4(was.a > 0.0 ? lerp(was.rgb, now, follow) : now, 1.0); +} +#endif + +#ifdef PLACE +[RootSignature(RS)] +[numthreads(8, 4, 1)] +void place(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(CX, CY)), size); + cells[CELLS + 1 + at.y * CX + at.x] = float4(p, p.z * p.z); +} +#endif + +#ifdef GATHER +[RootSignature(RS)] +[numthreads(8, 2, 1)] +void gather(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size); + float r2 = 0.25 + 0.0025 * p.z * p.z; + float whole = 0; + float3 toward = 0, light = 0, red = 0, green = 0, blue = 0; + for (uint i = 0; i < CELLS; i++) { + float4 c = cells[CELLS + 1 + i]; + float3 L = cells[i].rgb; + float3 d = c.xyz - p; + float dd = dot(d, d); + float w = c.w / (dd + r2); + float3 dir = d / sqrt(dd + 0.25 * r2); + whole += w; + toward += w * dir; + light += w * L; + red += w * L.r * dir; + green += w * L.g * dir; + blue += w * L.b * dir; + } + whole = max(whole, 1e-6); + light /= whole; + toward /= whole; + uint at0 = (at.y * PX + at.x) * 3; + points[at0] = float4(red / whole - light.r * toward, light.r); + points[at0 + 1] = float4(green / whole - light.g * toward, light.g); + points[at0 + 2] = float4(blue / whole - light.b * toward, light.b); +} +#endif + +#ifdef RAISE +RWTexture2D light : register(u0); +float3 unpack(uint v) { + return float3(v & 511, (v >> 9) & 511, (v >> 18) & 511) * exp2(float(v >> 27) - 24.0); +} +uint pack(float3 c) { + c = clamp(c, 0.0, 65408.0); + float top = max(c.r, max(c.g, c.b)); + int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31); + float scale = exp2(float(24 - e)); + if (top * scale >= 511.5) { e = min(e + 1, 31); scale = exp2(float(24 - e)); } + uint3 m = min(uint3(c * scale + 0.5), 511u); + return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); +} +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void raise(uint3 at : SV_DispatchThreadID) { + float2 size = float2(width, height); + if (at.x >= width || at.y >= height) return; + int2 p = int2(at.xy); + float3 c = seen(p, size); + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx) + float3(0, 0, -1e-9)); + if (dot(n, c) > 0.0) n = -n; + // How open it is (as in beloooo's cd9f78ce). + float open = 1.0; + float px = min(radius * size.y / (2.0 * tan_y * c.z), 128.0); + float noise = frac(52.9829189 * frac(dot(float2(p), float2(0.06711056, 0.00583715)))); + if (strength > 0.0 && px >= 1.5 && c.z < 400.0) { + float sum = 0.0; + const int N = 12; + for (int i = 0; i < N; i++) { + float a = i * 2.399963 + noise * 6.2831853; + float2 o = float2(cos(a), sin(a)) * (sqrt((i + 0.5) / N) * px); + float3 v = seen(p + int2(round(o)), size) - c; + float vv = dot(v, v); + float over = dot(v, n) - 0.004 * c.z - 0.005; + sum += max(over, 0.0) / sqrt(vv + 1e-6) * saturate(1.0 - vv / (radius * radius)); + } + open = saturate(1.0 - strength * 2.0 * sum / N); + } + float3 found; + if (constant > 0.0) { + found = float3(1.0, 0.98, 0.94) * constant * open; + light[p] = pack(found); + return; + } + // Between the four points around, those at its own depth first; which + // four is dithered a little. + float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5 + (noise - 0.5) * 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float4 sr = 0, sg = 0, sb = 0; + float sum = 0; + for (int k = 0; k < 4; k++) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z; + float2 b = float2(k & 1 ? f.x : 1 - f.x, k >> 1 ? f.y : 1 - f.y); + float w = (b.x * b.y + 1e-3) / (0.02 + abs(z - c.z) / c.z); + uint at0 = (q.y * PX + q.x) * 3; + sr += w * points[at0]; + sg += w * points[at0 + 1]; + sb += w * points[at0 + 2]; + sum += w; + } + float3 all = float3(sr.w, sg.w, sb.w) / sum; + found = all + 1.2 * float3(dot(sr.xyz, n), dot(sg.xyz, n), dot(sb.xyz, n)) / sum; + found = clamp(found, 0.2 * all, 2.5 * all); + found = lerp(found, cells[CELLS].rgb, 0.2) * level * open; + float3 was = unpack(light[p]); + // What the program left counts as far as it can be true: the sky's light + // outdoors, not the blocks of other memory. + float top = max(dot(found, LUMA) * most, 1e-6); + float has = dot(was, LUMA); + was *= min(1.0, top / max(has, 1e-6)); + light[p] = pack(max(was, found)); +} +#endif +"#; + +/// Bytes of the cells' buffer and of the points'. +const CELLS: u64 = 64 * 36; +const CELL_BYTES: u64 = (2 * CELLS + 1) * 16; +const POINT_BYTES: u64 = 160 * 90 * 48; + +struct Pass { + root: ID3D12RootSignature, + keep: ID3D12PipelineState, + mean: ID3D12PipelineState, + place: ID3D12PipelineState, + gather: ID3D12PipelineState, + raise: ID3D12PipelineState, + cells: ID3D12Resource, + points: ID3D12Resource, +} +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Pass {} +// SAFETY: as above. +unsafe impl Sync for Pass {} + +fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) -> windows::core::Result { + let mut root: Option = None; + let mut pipeline = |part: &str, entry| -> windows::core::Result { + let code = crate::host::compile(&format!("#define {part}\n{SOURCE}"), entry, s!("cs_5_1"))?; + // SAFETY: the root signature is inside the shader; plain creations. + unsafe { + if root.is_none() { + root = Some(device.CreateRootSignature(0, &code)?); + } + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() }, + ..Default::default() + }; + device.CreateComputePipelineState(&desc) + } + }; + let keep = pipeline("KEEP", s!("keep"))?; + let mean = pipeline("KEEP", s!("mean"))?; + let place = pipeline("PLACE", s!("place"))?; + let gather = pipeline("GATHER", s!("gather"))?; + let raise = pipeline("RAISE", s!("raise"))?; + let made = |bytes| buffer(bytes).ok_or_else(windows::core::Error::empty); + Ok(Pass { + root: root.ok_or_else(windows::core::Error::empty)?, + keep, + mean, + place, + gather, + raise, + cells: made(CELL_BYTES)?, + points: made(POINT_BYTES)?, + }) +} + +fn pass() -> Option<&'static Pass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let host = host()?; + make(&host.device, |bytes| host.uav_buffer(bytes)) + .inspect_err(|e| tracing::warn!(error = %e, "no stand-in for the indirect light")) + .ok() + }) + .as_ref() +} + +fn uav_barrier(list: &ID3D12GraphicsCommandList) { + let barrier = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() }; + // SAFETY: an open list; the barrier names no resource. + unsafe { list.ResourceBarrier(&[barrier]) }; +} + +/// Whether the light of a frame has been kept: the estimate has something +/// to begin with. +static KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// What the passes read and write, as views in the heap the list has set. +pub(crate) struct Views { + /// The image the title's program just wrote. + pub(crate) image: D3D12_GPU_DESCRIPTOR_HANDLE, + /// The scene's depth, for [`Role::Resolve`]. + pub(crate) depth: D3D12_GPU_DESCRIPTOR_HANDLE, + /// The size of the light's image. + pub(crate) size: [u32; 2], +} + +/// After the title's program of that role, in `list` with the program's view +/// heap set. Replaces the list's compute root signature and pipeline; false +/// if it recorded nothing. +pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { + use std::sync::atomic::Ordering; + let Some(pass) = pass() else { + return false; + }; + let (level, constant) = match set() { + Set::Off => return false, + Set::Estimate(level) => (level, 0.0f32), + Set::Constant(level) => (0.0, level), + }; + if role == Role::Resolve && constant == 0.0 && !KEPT.load(Ordering::Relaxed) { + return false; + } + static SAID: Mutex = Mutex::new(0); + { + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if *said < 4 { + *said += 1; + tracing::info!(?role, size = ?views.size, level, constant, "a stand-in for the indirect light"); + } + } + list.keep(&pass.cells); + list.keep(&pass.points); + let [strength, radius] = shade(); + let floats = [level, constant, strength, radius, 0.1, 0.45]; + let mut words = [0u32; 12]; + for (to, v) in words.iter_mut().zip(floats) { + *to = v.to_bits(); + } + words[6] = views.size[0]; + words[7] = views.size[1]; + words[8] = 0.04f32.to_bits(); + words[9] = 4.0f32.to_bits(); + let l = &list.list; + // SAFETY: an open list with the heap of the views set; the title's + // program has just used both views, so their textures are in the states + // these views need; buffers the list keeps. + unsafe { + uav_barrier(l); + l.SetComputeRootSignature(&pass.root); + l.SetComputeRoot32BitConstants(0, 12, words.as_ptr().cast(), 0); + l.SetComputeRootDescriptorTable(1, views.depth); + l.SetComputeRootDescriptorTable(2, views.image); + l.SetComputeRootUnorderedAccessView(3, pass.cells.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(4, pass.points.GetGPUVirtualAddress()); + let run = |pso: &ID3D12PipelineState, x, y| { + l.SetPipelineState(pso); + l.Dispatch(x, y, 1); + uav_barrier(l); + }; + match role { + Role::Radiance => { + run(&pass.keep, 8, 9); + run(&pass.mean, 1, 1); + KEPT.store(true, Ordering::Relaxed); + } + Role::Resolve => { + if constant == 0.0 { + run(&pass.place, 8, 9); + run(&pass.gather, 20, 45); + } + run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8)); + } + } + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings() { + assert_eq!(parse(""), Set::Off); + assert_eq!(parse("off"), Set::Off); + assert_eq!(parse("0"), Set::Off); + assert_eq!(parse("0.8"), Set::Estimate(0.8)); + assert_eq!(parse("constant:0.3"), Set::Constant(0.3)); + assert_eq!(parse("constant:nan"), Set::Off); + } + + #[test] + fn roles_by_name() { + assert_eq!(role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), Some(Role::Resolve)); + assert_eq!(role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), Some(Role::Radiance)); + assert_eq!(role(b"CS_TemporalResolve"), None); + } + + /// The passes compile with the system's compiler and the host takes them. + #[test] + fn the_passes_build() { + let Some(host) = host() else { + return; + }; + make(&host.device, |bytes| host.uav_buffer(bytes)).expect("the passes"); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c1bbae5..4ef4340 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -321,6 +321,10 @@ pub(crate) struct State { /// report of a removed device, `crate::host::indirects`). #[cfg(feature = "diagnostics")] user: Vec, + /// The tables the last bind made afresh for a program the stand-in for + /// the indirect light follows (`crate::ambient`): root parameter, bytes + /// into the view heap. + ambient_tables: Vec<(u8, u32)>, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -1449,6 +1453,10 @@ impl State { once!("a draw whose descriptor table found no free slots is dropped"); return false; } + if stage.shader.ambient.is_some() { + self.ambient_tables.clear(); + self.ambient_tables.extend(made.iter().copied()); + } // What the shader stores through root views and raw addresses is // copied back into title memory afterwards. let writes = (t.stores || !write_skip()) @@ -2603,6 +2611,62 @@ impl State { unsafe { list.list.Dispatch(x, y, z) }; self.buffers_written(); DISPATCHED.fetch_add(1, Ordering::Relaxed); + if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient) + && crate::ambient::on() + && self.ambient(list, p, role) + { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + } + + /// The stand-in for the indirect light after a dispatch of `p` + /// (`crate::ambient`). Whether it recorded anything. + fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { + use crate::ambient::{DEPTH, LIGHT, RADIANCE, Role, Views}; + let Some(t) = p.stages.first().map(|s| s.translated()) else { + return false; + }; + let Some(heap) = (self.heaps[0] != 0).then(|| crate::descriptor::heap(self.heaps[0] as This).host()).flatten() + else { + return false; + }; + let entry = |kind: ResourceType, (slot, offset): (u8, u32)| { + t.used.iter().find(|u| { + u.kind == kind && u.root == RootType::Table && (u.slot, u.table_offset_dwords) == (slot, offset) + })?; + let Some(Root::Table(table)) = self.roots_ref(true).get(usize::from(slot)) else { + return None; + }; + let resource = match crate::descriptor::view(table + u64::from(offset) * 4)? { + View::Shader(r, _) | View::Unordered(r, ..) => r, + _ => return None, + }; + let start = match self.ambient_tables.iter().find(|m| m.0 == slot) { + Some(m) => m.1, + None => self.user_value(true, slot, RootType::Table, 0), + }; + let host = crate::resource::host_resource(resource as This)?; + // SAFETY: a live resource. + let desc = unsafe { host.GetDesc() }; + Some((desc, heap.gpu_handle((start + offset * 4) / 32))) + }; + let image = entry(ResourceType::Uav, if role == Role::Resolve { LIGHT } else { RADIANCE }); + let depth = match role { + Role::Resolve => entry(ResourceType::Srv, DEPTH), + Role::Radiance => image, + }; + let (Some((of, image)), Some((seen, depth))) = (image, depth) else { + once!(?role, "no stand-in for the indirect light: other tables"); + return false; + }; + // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) + let format = if role == Role::Resolve { 42 } else { 26 }; + if of.Format.0 != format || (seen.Width, seen.Height) != (of.Width, of.Height) { + once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image"); + return false; + } + crate::ambient::after(list, role, &Views { image, depth, size: [of.Width as u32, of.Height] }) } /// What a draw or dispatch runs, for the device-removed report diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 29947a7..604f298 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -15,6 +15,8 @@ //! share, [`console`] which console model the title sees. Planned: //! `present` (swap chain). +#[cfg(windows)] +mod ambient; #[cfg(all(windows, feature = "diagnostics"))] mod capture; pub mod console; diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 7a00633..d64b06b 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -61,6 +61,9 @@ pub(crate) struct Shader { /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, container: Vec, + /// Its part in the stand-in for the indirect light. + #[cfg(windows)] + pub(crate) ambient: Option, #[cfg(windows)] translated: OnceLock>, } @@ -112,6 +115,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { hash: full.to_hex()[..16].to_owned(), container: bytes.to_vec(), #[cfg(windows)] + ambient: (stage == "compute").then(|| crate::ambient::role(bytes)).flatten(), + #[cfg(windows)] translated: OnceLock::new(), }) }) From 37332f4d6c37853b48d4d1a5340e119b8c0ad668 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:32:41 -0600 Subject: [PATCH 10/31] Parts of submissions prepared as one (VICTORY_JOIN_PARTS=8; off), fills cut free of copies at their place (VICTORY_PLACED_ORDER) The thread that runs the line takes the Run entries that follow in the queue along, with the waits they meet themselves and the signals between them (the idea: fxceless/victory-fork 39731795), as long as nothing of them reads on the CPU what those before them write; what they refresh is brought up to date in one go in front (VICTORY_REFRESH_FRONT on its own: measured at nothing); each part still goes to the queue in a call of its own. Run submit-1, the dorm: 12 of 28 parts joined, 54.8 -> 51.4 ms a frame of that thread. A copy at its place in a list is in the way of fills done on the card only from its place on, and the submission is cut behind its list for those (opening, run n19: 40-60 ms a frame of the submitting thread standing). Not seen in the dorm; not measured yet. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 393 ++++++++++++++++++++-- crates/victory-gpu/src/host/card_steps.rs | 199 +++++++---- crates/victory-gpu/src/queue/behind.rs | 183 +++++++++- 3 files changed, 673 insertions(+), 102 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7702f90..126a292 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2944,6 +2944,87 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc`; off by default, 1; `VICTORY_JOIN_LISTS`, +/// 48). +/// +/// The idea is fxceless/victory-fork's, commit 39731795 (GPL-3.0-or-later, as +/// this): the title's lists wait for memory values, which cuts a frame into +/// some 29 parts, each prepared on its own: the write watch asked, the heaps' +/// records, the title's bytes under the flights' writes, a list that sends +/// what changed and one that compares. (Run submit-1, the dorm, 12 of 28 parts +/// joined, eight at most: the thread works 51.4 ms a frame instead of 54.8, the +/// frame is 0.6 to 3 ms shorter.) What differs here: the parts are taken +/// off one queue's entries of the line (`crate::queue`), still go to the queue +/// in calls of their own, and everything they refresh is brought up to date in +/// front of the first ([`refresh_front`], without which a later part's title +/// bytes under an earlier part's declared writes would go missing). +pub(crate) fn joins() -> (usize, usize) { + if ahead_of_writes() { joins_asked() } else { (1, 1) } +} + +fn joins_asked() -> (usize, usize) { + static MOST: OnceLock<(usize, usize)> = OnceLock::new(); + let of = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let (parts, lists) = *MOST.get_or_init(|| (of("VICTORY_JOIN_PARTS").unwrap_or(1).max(1), of("VICTORY_JOIN_LISTS").unwrap_or(48).max(1))); + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_JOIN_PARTS") { + return (if on { 8 } else { 1 }, lists); + } + (parts, lists) +} + +/// Whether the part `next` can be prepared together with `ahead`, which goes +/// before it and has not been sent: nothing done on the CPU for it reads what +/// those give their shaders, write back or write when they are done, and it +/// changes no title memory that they read ([`Step::Copy`], [`Step::Run`]). +pub(crate) fn joinable<'a>(ahead: impl Iterator, next: &[&HostList]) -> bool { + if next.iter().any(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Copy(..) | Step::Run(_)))) { + return false; + } + let ahead: Vec<&HostList> = ahead.collect(); + let mut written: Vec<(usize, usize)> = declared_writes(&ahead).into_iter().flat_map(|(_, ranges)| ranges).collect(); + for list in &ahead { + let deferred = list.deferred(); + written.extend(deferred.writes.iter().map(|&(at, _, bytes)| (at, at + bytes))); + written.extend(deferred.backs.iter().map(|&(_, at, [row, rows, pitch])| (at, at + rows.saturating_sub(1) * pitch + row))); + } + let mut joined = Vec::new(); + join_ranges(&mut joined, written); + blocked_by(&joined, next, false).is_none() +} + +/// Whether a bottom-of-pipe write of `list` meets `wait`. +pub(crate) fn will_meet(list: &HostList, wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + // The last write there says. + let deferred = list.deferred(); + let last = deferred.writes.iter().rev().find(|(at, _, n)| *at < address + bytes && address < *at + *n); + matches!(last, Some((at, crate::queue::Written::Value(v), n)) if *at == address && *n >= bytes && wait.holds_for(*v)) +} + +/// Lists and the order they run in. +type Run = (Vec, Vec); + +/// `order`'s first `cut` places and the rest, each with the lists they name; +/// as it was if a list is named on both sides. +fn split(lists: Vec, order: Vec, cut: usize) -> Result<[Run; 2], Run> { + let (first, second) = order.split_at(cut); + if first.is_empty() || second.is_empty() || first.iter().any(|i| second.contains(i)) { + return Err((lists, order)); + } + let behind: Vec = (0..lists.len()).map(|i| second.contains(&i)).collect(); + let place = |i: usize| behind[..i].iter().filter(|&&b| b == behind[i]).count(); + let orders = [first, second].map(|half| half.iter().map(|&i| place(i)).collect::>()); + let mut halves: [Vec; 2] = [Vec::new(), Vec::new()]; + for (list, behind) in lists.into_iter().zip(&behind) { + halves[usize::from(*behind)].push(list); + } + let [a, b] = halves; + let [x, y] = orders; + Ok([(a, x), (b, y)]) +} + /// A fence signal on a queue ([`late`]): goes behind the flights in the /// air, if there are any, and is set when they are settled. Whether it /// did; if not the caller sets the fence now. @@ -2973,11 +3054,20 @@ pub(crate) fn late_signal(fence: usize, value: u64) -> bool { /// the value in a way not known here (shaders, a timestamp, another /// width), they are settled and memory is asked again. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { + if let Some(met) = late_met_known(wait) { + return met; + } + settle_now(WHY_VALUE); + wait.met() +} + +/// [`late_met`] without a wait for the card; `None`: it has to be waited for. +pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> Option { let (address, bytes) = wait.place(); { let line = line(); if line.line.is_empty() && line.in_hand.is_empty() { - return false; + return Some(false); } let mut unsure = touches(&line.written, address, address + bytes); // (With the relay: first the writes of flights being landed.) @@ -2993,18 +3083,17 @@ pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { crate::queue::Written::Value(v) if *at == address && *n >= bytes => { if wait.holds_for(*v) { LATE_STATS[13].fetch_add(1, Ordering::Relaxed); - return true; + return Some(true); } } _ => unsure = true, } } if !unsure { - return false; + return Some(false); } } - settle_now(WHY_VALUE); - wait.met() + None } /// Settles the flights in the air, if any ([`Host::settle`]), for reason @@ -4016,30 +4105,13 @@ impl Host { /// `relay`). /// `picked`: ranges that may be written too, and ranges to look at /// (`crate::picked`). - fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option { + fn card_before(&self, declared: &[Declared], picked: &crate::picked::Ranges, flown: bool) -> Option { use std::sync::Arc; if !crate::shadow::cards() { return None; } // The ranges this submission's shaders may write, per copy. - let mut declared: Vec<(Arc, Vec<(usize, usize)>)> = Vec::new(); - for list in runs { - for step in &list.deferred().copies { - if let Step::GpuWrite(shadow, address, len) = step - && shadow.carded() - { - let range = (*address, *address + *len); - match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) { - Some((_, ranges)) => { - if !ranges.contains(&range) { - ranges.push(range); - } - } - None => declared.push((shadow.clone(), vec![range])), - } - } - } - } + let declared: Vec = declared.iter().filter(|(shadow, _)| shadow.carded()).cloned().collect(); let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared }; // (Of a copy with a declared range here, that says it.) let looked: Vec<&crate::picked::Range> = @@ -4883,7 +4955,7 @@ impl Host { pub(crate) fn execute(&self, runs: &[&HostList]) { // Behind what the title's queues were given before it. crate::queue::before_sync(); - let _ = self.submit(runs, false); + let _ = self.submit(runs, &[], false); } /// A queue's submission with [`late`]: the host lists `lists`, taken @@ -4893,14 +4965,39 @@ impl Host { /// ([`late`] lists those points); their host lists are reset and kept /// for reuse then, as a queue does for the lists it ran. pub(crate) fn execute_late(&self, lists: Vec, order: Vec) { + self.execute_parts(lists, order, &[]); + } + + /// [`Host::execute_late`] of parts of submissions in one: another begins + /// at each place of `order` in `parts` ([`joins`]). + pub(crate) fn execute_parts(&self, lists: Vec, order: Vec, parts: &[usize]) { if order.is_empty() { crate::list::recycle(lists, &order); return; } late_threads(); + if let Some(cut) = { + let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); + card_steps::cut_for(&runs) + } { + match split(lists, order, cut) { + Ok([(lists, order), (more, behind)]) => { + let first: Vec = parts.iter().copied().filter(|&p| p < cut).collect(); + let second: Vec = parts.iter().filter(|&&p| p > cut).map(|p| p - cut).collect(); + self.execute_parts(lists, order, &first); + self.execute_parts(more, behind, &second); + } + Err((lists, order)) => self.send_late(lists, order, parts), + } + return; + } + self.send_late(lists, order, parts); + } + + fn send_late(&self, lists: Vec, order: Vec, parts: &[usize]) { let sent = { let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); - self.submit(&runs, true) + self.submit(&runs, parts, true) }; let Some((mut submitted, sent)) = sent else { // (Not reached: a submission sent ahead always comes back.) @@ -4950,7 +5047,7 @@ impl Host { /// it ran and was waited for after all. fn execute_own(&self, list: &HostList) -> u64 { late_threads(); - let Some((submitted, sent)) = self.submit(&[list], true) else { + let Some((submitted, sent)) = self.submit(&[list], &[], true) else { return 0; }; let number = sent.number; @@ -5172,7 +5269,11 @@ impl Host { /// [`Host::execute_late`]: the lists are prepared and sent, and what is /// to be done once they have run comes back with the submission lock /// still held. - fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> { + /// + /// `parts`: the lists of `runs` at which another part begins + /// ([`joins`]): those go to the queue in calls of their own, one after the + /// other, as they would have. + fn submit<'a>(&'a self, runs: &[&HostList], parts: &[usize], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> { #[cfg(feature = "diagnostics")] let called = std::time::Instant::now(); #[cfg(feature = "diagnostics")] @@ -5225,6 +5326,7 @@ impl Host { } None => runs, }; + let parts: Vec = parts.iter().map(|&n| n + usize::from(own.is_some())).collect(); stage.next("submit: the sweep"); let behind = late && flying(); // Before this submission counts as started: what the sweep lets go @@ -5320,7 +5422,9 @@ impl Host { // What flights in the air may write. let air = line().written.clone(); stage.next("submit: refreshes ahead of writes"); - if ahead_of_writes() { + if refresh_front() { + batch.refresh_front(runs, &parts); + } else if ahead_of_writes() { batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i))); } stage.next("submit: the lists' steps"); @@ -5367,7 +5471,8 @@ impl Host { for (shadow, at, len) in &picked.written { shadow.writing(*at, *len); } - let card = self.card_before(runs, &picked, flown); + let declared = declared_writes(runs); + let card = self.card_before(&declared, &picked, flown); // The sends are taken: from here on the references hold what the // copies in the lists put. for (shadow, at, bytes) in batch.placed.drain(..) { @@ -5404,10 +5509,16 @@ impl Host { if let Some([front, behind]) = self.span_lists() { lists.insert(0, Some(front)); lists.push(Some(behind)); + firsts.iter_mut().for_each(|first| *first += 1); } + let cuts: Vec = parts.iter().filter_map(|&n| firsts.get(n).copied()).collect(); // SAFETY: closed lists; the fence is ours. let signalled = unsafe { - self.queue.ExecuteCommandLists(&lists); + let mut from = 0; + for to in cuts.into_iter().chain([lists.len()]) { + self.queue.ExecuteCommandLists(&lists[from..to]); + from = to; + } self.queue.Signal(&self.fence, *submitted) }; awake::sent(&self.device); @@ -5420,7 +5531,7 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(5); - let back = crate::picked::with(declared_writes(runs), &picked.written); + let back = crate::picked::with(declared, &picked.written); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); submitting(0, 0); @@ -5545,7 +5656,7 @@ impl Host { if let Some(card) = &card { self.card_back(card, &mut submitted, &mut std::collections::HashSet::new()); } - let back = crate::picked::with(declared_writes(runs), &picked.written); + let back = crate::picked::with(declared, &picked.written); hand_back(&back); if let Some(card) = card { self.card_done(card); @@ -7182,6 +7293,9 @@ struct Batch { /// Copies (by address) brought up to date ahead of the steps, and the /// range (from, to) ([`Batch::refresh_ahead`]). ahead: ByCopy<(usize, usize)>, + /// `ahead` holds everything the submission refreshes + /// ([`Batch::refresh_front`]). + front: bool, } /// Whether the copies that a submission's shaders write are brought up to @@ -7195,6 +7309,73 @@ fn ahead_of_writes() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light()) } +/// Whether everything a submission refreshes is brought up to date in one go, +/// on several threads, ahead of its steps (`VICTORY_REFRESH_FRONT=1`, and with +/// `VICTORY_JOIN_PARTS`, which needs it; else in groups where the steps ask +/// for it). Measured on its own at nothing (run submit-1: refreshes 17.1 ms a +/// frame without, 18.3 with). +/// +/// A submission's refreshes were done in up to five groups one after the other +/// (the copies its shaders write, those between its steps, what is left), +/// each ending with the threads waiting for the last copy; and the submitting +/// thread went over all the steps once for each question it has (what to ask +/// about, what flights may write too, what shaders write). A refresh may come +/// earlier than its step: the title's bytes are the same until a step writes +/// title memory, and behind such a step everything is asked for again, as it +/// was. +fn refresh_front() -> bool { + static ON: OnceLock = OnceLock::new(); + ahead_of_writes() && (joins_asked().0 > 1 || *ON.get_or_init(|| crate::switch::on("VICTORY_REFRESH_FRONT"))) +} + +/// Per copy what is refreshed in front of a submission's steps, as +/// [`written_spans`]'s but of all copies, up to the copy's first write by +/// shaders in each part of the submission (`Touch::Part`: another begins). +/// What a part refreshes of a copy it has given to its shaders stays where it +/// stands: around what they write. What a later part refreshes is the +/// title's bytes of before either. +fn front_spans(steps: impl Iterator) -> Vec<(usize, usize, usize)> { + let mut at: ByCopy = ByCopy::default(); + // (Copy, from, to), in the order they come, and the part that gave it to + // shaders last. + let mut spans: Vec<(usize, usize, usize)> = Vec::new(); + let mut given: Vec = Vec::new(); + let (mut part, mut last) = (1, usize::MAX); + for step in steps { + match step { + Touch::Refresh(copy, from, to) => { + // (Most come several times on end.) + let i = if spans.get(last).is_some_and(|s| s.0 == copy) { + last + } else { + *at.entry(copy).or_insert_with(|| { + spans.push((copy, usize::MAX, 0)); + given.push(0); + spans.len() - 1 + }) + }; + last = i; + if given[i] != part { + let span = &mut spans[i]; + (span.1, span.2) = (span.1.min(from), span.2.max(to)); + } + } + Touch::Write(copy) => { + let i = *at.entry(copy).or_insert_with(|| { + spans.push((copy, usize::MAX, 0)); + given.push(0); + spans.len() - 1 + }); + given[i] = part; + } + Touch::Part => part += 1, + Touch::Title | Touch::Nothing => {} + } + } + spans.retain(|s| s.1 < s.2); + spans +} + /// What a step is to the copies' refreshes, for [`written_spans`]. enum Touch { /// A refresh of a copy (by address), from, to. @@ -7204,6 +7385,8 @@ enum Touch { /// Title memory is written. Title, Nothing, + /// Another part of the submission begins. + Part, } /// Of `steps`, up to the first that writes title memory: the copies given to @@ -7226,7 +7409,7 @@ fn written_spans(steps: impl Iterator) -> Vec<(usize, usize, usize } } Touch::Title => break, - Touch::Nothing => {} + Touch::Nothing | Touch::Part => {} } } spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect() @@ -7234,7 +7417,47 @@ fn written_spans(steps: impl Iterator) -> Vec<(usize, usize, usize #[cfg(test)] mod written_spans_tests { - use super::{Touch, written_spans}; + use super::{Touch, front_spans, split, written_spans}; + + #[test] + fn everything_is_refreshed_in_front_but_what_a_part_gave_its_shaders() { + use Touch::{Nothing, Part, Refresh, Title, Write}; + let found = front_spans( + [ + Refresh(1, 10, 20), + Refresh(1, 12, 25), + Refresh(2, 0, 5), + Nothing, + Write(1), + // (Around what the part's own shaders write.) + Refresh(1, 0, 100), + Write(3), + Refresh(3, 1, 2), + Title, + Refresh(4, 7, 9), + Part, + // The next part's bytes under the first one's writes. + Refresh(1, 30, 40), + Write(4), + Refresh(4, 0, 9), + ] + .into_iter(), + ); + assert_eq!(found, [(1, 10, 40), (2, 0, 5), (4, 7, 9)]); + } + + #[test] + fn a_submission_is_cut_between_its_lists() { + // Lists c and e are in neither half's order: they go with the first. + let Ok([first, second]) = split(vec!['a', 'b', 'c', 'd', 'e'], vec![1, 3, 0], 1) else { + panic!("no list is named twice"); + }; + let run = |(lists, order): &(Vec, Vec)| order.iter().map(|&i| lists[i]).collect::(); + assert_eq!((run(&first), run(&second)), ("b".into(), "da".into())); + assert_eq!(first.0.len() + second.0.len(), 5); + assert!(split(vec!['a', 'b'], vec![0, 1, 0], 2).is_err()); + assert!(split(vec!['a', 'b'], vec![0, 1], 0).is_err()); + } #[test] fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() { @@ -7315,8 +7538,11 @@ impl Batch { /// Before shaders are given a range of `shadow`'s copy: its pending /// refresh is done, the others stay pending. fn flush_one(&mut self, shadow: &std::sync::Arc) { - // From here on it is refreshed around what the shaders write. - self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize)); + // From here on it is refreshed around what the shaders write. (What + // is in front of all the steps was, up to here.) + if !self.front { + self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize)); + } let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { return; }; @@ -7365,6 +7591,99 @@ impl Batch { self.textures.clear(); } + /// Before the steps of `runs` ([`refresh_front`]), a new part of the + /// submission beginning at each of `parts`. + fn refresh_front(&mut self, runs: &[&HostList], parts: &[usize]) { + let mut copies: ByCopy> = ByCopy::default(); + let mut due = Vec::new(); + let mut touches = Vec::new(); + for (n, list) in runs.iter().enumerate() { + if parts.contains(&n) { + touches.push(Touch::Part); + } + let mut last = 0; + for step in &list.deferred().copies { + match step { + Step::Refresh(shadow, at, len) => { + let key = std::sync::Arc::as_ptr(shadow) as usize; + if key != last { + copies.entry(key).or_insert_with(|| shadow.clone()); + last = key; + } + touches.push(Touch::Refresh(key, *at, *at + *len)); + } + Step::GpuWrite(shadow, ..) => touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)), + Step::Texture(staging) if wide_textures() => { + if self.texture_due(staging) { + due.push(staging.clone()); + } + } + _ => {} + } + } + } + let spans: Vec<_> = front_spans(touches.into_iter()) + .into_iter() + .filter_map(|(key, from, to)| Some((copies.remove(&key)?, from, to))) + .collect(); + self.front = true; + for (shadow, from, to) in &spans { + self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to)); + } + #[cfg(feature = "diagnostics")] + { + FLUSHES[0].fetch_add(1, Ordering::Relaxed); + FLUSHES[1].fetch_add(spans.len() as u64, Ordering::Relaxed); + } + let _flush = crate::timeline::span("refreshes of copies"); + let started = std::time::Instant::now(); + let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)); + // Those known to copy nothing are said so here, unless they are very + // many: then beside the others. + const FEW: usize = 256; + let mut spans = spans; + let many = spans.len() > FEW; + if !many { + #[cfg(feature = "diagnostics")] + let all = spans.len(); + spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + #[cfg(feature = "diagnostics")] + FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed); + } + let ahead = spans.len() > 1; + if ahead { + let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect(); + crate::watch::ask_ahead(&ranges); + } + #[cfg(feature = "diagnostics")] + FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); + crate::shadow::wide_each(spans.len() + due.len(), move |i| { + // The textures first: they are the longer pieces. + let Some(i) = i.checked_sub(due.len()) else { + due[i].refresh(); + return; + }; + let (shadow, from, to) = &spans[i]; + if many && shadow.nothing_new(*from, *to - *from) { + #[cfg(feature = "diagnostics")] + FLUSHES[2].fetch_add(1, Ordering::Relaxed); + return; + } + Self::update(shadow, *from, *to); + }); + if ahead { + crate::watch::ask_ahead_done(); + } + // The time counted is the time it took, not the threads' sum. + let took = started.elapsed().as_micros() as u64; + let summed = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)).iter().zip(before).map(|(now, was)| now.saturating_sub(was)).collect::>(); + PREPARING[2].fetch_sub(summed[1], Ordering::Relaxed); + PREPARING[0].fetch_sub(summed[0], Ordering::Relaxed); + PREPARING[0].fetch_add(took, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + } + /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills /// that `taken` names are not done on the CPU. fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) { diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 2d711c3..9790941 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -83,6 +83,23 @@ pub(super) fn stage() -> u32 { }) } +/// Whether a copy at its place in a list ([`place`]) is only in the way of +/// what is done on the card in front of the lists if that stands behind it in +/// them (`VICTORY_PLACED_ORDER=0`: wherever it stands, as before), and a +/// submission where it does is cut behind the copy's list ([`cut_for`]). +/// +/// The fills of constant buffers read the title's ring (7,500 a frame in the +/// opening), and one copy of a few hundred bytes a frame writes into it at its +/// place in a list. The whole submission was refused for it, and stood 40 to +/// 60 ms until the flights had landed (run n19). +fn placed_order() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PLACED_ORDER").is_none_or(|v| v != "0")) +} + +/// Why [`plan`] refuses for [`place`]. +const BEHIND_PLACED: &str = "a copy at its place in a list writes what it reads, or reads or writes what it writes"; + /// The bytes of our buffer between reading and writing: what one submission /// may do this way (each place read once, however many fills take it). const BETWEEN: u64 = 4 << 20; @@ -226,10 +243,13 @@ fn touched(ranges: &[(usize, usize)], r: (usize, usize)) -> bool { /// only what a taken copy has not been told to write yet: bytes a step /// ahead of it reads, in title memory as it is. /// +/// `behind`: for [`BEHIND_PLACED`], the copy at its place and the first step +/// behind it that is in its way. +/// /// Steps of a level are done together, every read before every write; a /// step that writes what an earlier one reads or writes, or reads what it /// writes, is of a higher level. Our list does them level by level. -fn plan(does: &[Does], stage: u32) -> Result, &'static str> { +fn plan(does: &[Does], stage: u32, by_order: bool, behind: &mut Option<(usize, usize)>) -> Result, &'static str> { let takes = |d: &Does| match *d { Does::Copy { .. } if stage < 2 => Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"), Does::Fill { to: false, .. } => Err("a fill of memory the card cannot be given the bytes of"), @@ -281,12 +301,21 @@ fn plan(does: &[Does], stage: u32) -> Result, &'static str> { } } // A copy at its place in a list comes after what is done in front of all - // of them. - for d in does { + // of them: as it should after the steps ahead of it, but not after those + // behind it that read or write its bytes. + for (p, d) in does.iter().enumerate() { if let Does::Placed { dst, src, len } = *d && (touched(&read, (dst, dst + len)) || touched(&written, (dst, dst + len)) || touched(&written, (src, src + len))) { - return Err("a copy at its place in a list writes what it reads, or reads or writes what it writes"); + let (to, from) = ((dst, dst + len), (src, src + len)); + let in_the_way = |i: usize| { + reads_writes(&does[i]).is_some_and(|(r, w)| meet(r, to) || w.0 < w.1 && (meet(w, to) || meet(w, from))) + }; + let found = (p + 1..does.len()).find(|&i| taken[i] && in_the_way(i)); + *behind = found.map(|i| (p, i)); + if !by_order || found.is_some() { + return Err(BEHIND_PLACED); + } } } let order: Vec = (0..does.len()).filter(|&i| taken[i]).collect(); @@ -375,6 +404,78 @@ fn holder(writers: &[Writer], from: usize, to: usize) -> Result, &'s Ok(shadow) } +/// What the steps of `runs` do, and which step each is (its list by address, +/// its place in it). `written`: what flights may write. +fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec, Vec<(usize, usize)>) { + let mut does = Vec::new(); + // Which step each is. One list's lock at a time: a submission may + // name a list twice. + let mut steps = Vec::new(); + for list in runs { + for (i, step) in list.deferred().copies.iter().enumerate() { + does.push(match step { + &Step::Copy(dst, src, len) => Does::Copy { + dst, + src, + len, + asked: copy_blocked(written, dst, src, len).is_some(), + }, + Step::Fill(_, src, len, to) => Does::Fill { + src: *src, + len: *len, + asked: read_blocked(written, *src, *len), + to: to.is_some(), + }, + Step::Texture(staging) => { + let (at, len) = staging.memory(); + Does::Read { + from: at, + to: at + len, + asked: touches(written, at, at + len), + } + } + &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false }, + Step::Refresh(shadow, at, len) => Does::Refresh { + shadow: Arc::as_ptr(shadow) as usize, + from: *at, + to: *at + *len, + }, + Step::Run(_) => Does::Run, + Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len }, + Step::GpuWrite(..) | Step::Host(..) => continue, + }); + steps.push((std::ptr::from_ref::(list) as usize, i)); + } + } + (does, steps) +} + +/// With flights in the air: before which of `runs` the submission is cut so +/// that what reads or writes the bytes of a copy at its place in an earlier +/// list ([`BEHIND_PLACED`]) is done on the card in front of a submission of +/// its own, behind that copy. +pub(super) fn cut_for(runs: &[&HostList]) -> Option { + if stage() == 0 || !relay_exact() || !placed_order() || runs.len() < 2 { + return None; + } + // (Most submissions have none.) + let first = runs.iter().position(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Placed(_))))?; + if first + 1 == runs.len() { + return None; + } + let written = line().written.clone(); + blocked_by(&written, runs, false)?; + let (does, steps) = does_of(&written, runs); + let mut behind = None; + if plan(&does, stage(), true, &mut behind) != Err(BEHIND_PLACED) { + return None; + } + let (placed, reader) = behind?; + let place = |i: usize| runs.iter().position(|l| std::ptr::from_ref::(l) as usize == steps[i].0); + let cut = place(placed)? + 1; + (place(reader)? >= cut).then_some(cut) +} + /// Whether every page of `[from, to)` can be read (through the kernel: /// asking Windows walks the page tables, milliseconds in the title's heap). /// `room`: for what is read. @@ -567,47 +668,8 @@ impl Host { } fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result, &'static str> { - let mut does = Vec::new(); - // Which step each is. One list's lock at a time: a submission may - // name a list twice. - let mut steps = Vec::new(); - for list in runs { - for (i, step) in list.deferred().copies.iter().enumerate() { - does.push(match step { - &Step::Copy(dst, src, len) => Does::Copy { - dst, - src, - len, - asked: copy_blocked(written, dst, src, len).is_some(), - }, - Step::Fill(_, src, len, to) => Does::Fill { - src: *src, - len: *len, - asked: read_blocked(written, *src, *len), - to: to.is_some(), - }, - Step::Texture(staging) => { - let (at, len) = staging.memory(); - Does::Read { - from: at, - to: at + len, - asked: touches(written, at, at + len), - } - } - &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false }, - Step::Refresh(shadow, at, len) => Does::Refresh { - shadow: Arc::as_ptr(shadow) as usize, - from: *at, - to: *at + *len, - }, - Step::Run(_) => Does::Run, - Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len }, - Step::GpuWrite(..) | Step::Host(..) => continue, - }); - steps.push((std::ptr::from_ref::(list) as usize, i)); - } - } - let chosen = plan(&does, stage())?; + let (does, steps) = does_of(written, runs); + let chosen = plan(&does, stage(), placed_order(), &mut None)?; if chosen.is_empty() { return Ok(None); } @@ -863,7 +925,7 @@ mod tests { /// What is done on the card, as (place, level), in stage 2. fn planned(does: &[Does]) -> Vec<(usize, u32)> { - plan(does, 2).unwrap() + plan(does, 2, true, &mut None).unwrap() } /// Only what is asked for is taken, all of it, and a step that stands @@ -881,8 +943,8 @@ mod tests { ]; assert_eq!(planned(&does), [(1, 0), (3, 0)]); // Two fills of the same bytes. - assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![(0, 0), (1, 0)])); - assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![])); + assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1, true, &mut None), Ok(vec![(0, 0), (1, 0)])); + assert_eq!(plan(&[fill(0, 64, false)], 1, true, &mut None), Ok(vec![])); // Ends that touch are apart. let does = [ copy(1000, 5000, 100, true), @@ -927,6 +989,29 @@ mod tests { assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]); } + /// A copy at its place in a list is in the way of what reads or writes its + /// bytes behind it, not of what did ahead of it. + #[test] + fn copies_at_their_place_stand_in_the_way_of_what_is_behind_them() { + let placed = Does::Placed { dst: 2000, src: 3000, len: 64 }; + let behind = |does: &[Does]| { + let mut found = None; + let refused = plan(does, 2, true, &mut found); + assert!(refused.is_ok() || found.is_some() && refused == Err(BEHIND_PLACED)); + assert_eq!(plan(does, 2, false, &mut None).is_err(), does.len() > 1 && !matches!(does, [_, Does::Fill { src: 5000, .. }])); + found + }; + assert_eq!(behind(&[fill(2032, 64, true), placed]), None); + assert_eq!(behind(&[placed, fill(2032, 64, true)]), Some((0, 1))); + assert_eq!(behind(&[placed, fill(5000, 64, true)]), None); + assert_eq!(behind(&[fill(2000, 8, true), placed, fill(2000, 8, true)]), Some((1, 2))); + // One that writes what it copies from, and one that writes over it. + assert_eq!(behind(&[copy(3000, 5000, 8, true), placed]), None); + assert_eq!(behind(&[placed, copy(3000, 5000, 8, true)]), Some((0, 1))); + assert_eq!(behind(&[copy(2060, 5000, 8, true), placed]), None); + assert_eq!(behind(&[placed, copy(2060, 5000, 8, true)]), Some((0, 1))); + } + /// Whatever the steps, done level by level (in a level every read /// before every write) they read and leave what they read and leave one /// after the other, the CPU's steps ahead of all of them. @@ -951,7 +1036,7 @@ mod tests { } }) .collect(); - let Ok(chosen) = plan(&does, 2) else { + let Ok(chosen) = plan(&does, 2, true, &mut None) else { refused += 1; continue; }; @@ -1005,22 +1090,22 @@ mod tests { #[test] fn steps_in_the_way_are_refused() { let taken = copy(1000, 5000, 100, true); - assert!(plan(&[taken, Does::Run], 2).is_err()); + assert!(plan(&[taken, Does::Run], 2, true, &mut None).is_err()); // A texture that itself waits for flights; a fill that cannot be // taken but waits. - assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2).is_err()); - assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2).is_err()); + assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2, true, &mut None).is_err()); + assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2, true, &mut None).is_err()); // Reads on the CPU of what it writes: behind it, not ahead of it. for read in [Does::Read { from: 900, to: 1001, asked: false }, stuck(1050, 3)] { - assert!(plan(&[taken, read], 2).is_err(), "{read:?} behind"); + assert!(plan(&[taken, read], 2, true, &mut None).is_err(), "{read:?} behind"); assert_eq!(planned(&[read, taken]), [(1, 0)], "{read:?} ahead"); } // Also of what is taken along. - assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2).is_err()); + assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2, true, &mut None).is_err()); // Into itself, and copies without stage 2. - assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err()); - assert!(plan(&[taken], 1).is_err()); - assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err()); + assert!(plan(&[copy(1000, 1050, 100, true)], 2, true, &mut None).is_err()); + assert!(plan(&[taken], 1, true, &mut None).is_err()); + assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1, true, &mut None).is_err()); } #[test] diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index b2f3de7..8919ca9 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -61,6 +61,14 @@ pub(super) trait Work: Send { fn shows(&self) -> bool; /// Whether it is a submission. fn runs(&self) -> bool; + /// Takes `next`, what its queue was given behind it, along to be done with + /// it; or gives it back. Whether it is a submission that was taken. + fn take_along(&mut self, next: Self) -> Result + where + Self: Sized, + { + Err(next) + } /// Does it. `forced`: its wait was not met. fn go(self, forced: bool); } @@ -263,7 +271,7 @@ impl Lane { (first, true) } }; - let entry = { + let mut entry = { let mut state = self.lock(); let Some(at) = state.items.iter().position(|e| e.number == number) else { return false; @@ -274,13 +282,34 @@ impl Lane { state.running = Some(entry.queue); entry }; - let (shows, runs) = (entry.what.shows(), entry.what.runs()); + let (shows, mut runs) = (entry.what.shows(), usize::from(entry.what.runs())); + // What follows it in its queue, if that can go with it. (Nobody else + // takes anything out, and what comes in goes to the end.) + while runs > 0 && !forced { + let next = { + let mut state = self.lock(); + let at = state.items.iter().position(|e| e.queue == entry.queue && e.number < limit); + at.and_then(|at| state.items.remove(at)) + }; + let Some(Entry { number, queue, what }) = next else { + break; + }; + match entry.what.take_along(what) { + Ok(run) => runs += usize::from(run), + Err(what) => { + let mut state = self.lock(); + let at = state.items.iter().position(|e| e.number > number).unwrap_or(state.items.len()); + state.items.insert(at, Entry { number, queue, what }); + break; + } + } + } entry.what.go(forced); { let mut state = self.lock(); state.running = None; state.presents -= usize::from(shows); - state.runs -= usize::from(runs); + state.runs -= runs; } self.moved.notify_all(); true @@ -296,6 +325,9 @@ enum Job { /// A submission, or a part of one: the lists' host sides and the order /// they run in. Run(usize, Vec, Vec), + /// Parts taken along with a submission ([`crate::host::joins`]): where they + /// begin in the order, and the signals given behind them. + Joined(usize, Vec, Vec, Vec, Vec<(usize, u64)>), /// A signal of the queue's. Signal(usize, u64), /// A frame is shown: the texture and the state its lists leave it in. @@ -335,13 +367,73 @@ impl Work for Job { } fn runs(&self) -> bool { - matches!(self, Job::Run(..)) + matches!(self, Job::Run(..) | Job::Joined(..)) + } + + fn take_along(&mut self, next: Job) -> Result { + let (most, most_lists) = crate::host::joins(); + if most < 2 { + return Err(next); + } + // Nothing but waits and signals that a submission may follow. + let (count, lists, signals) = match self { + Job::Run(_, lists, order) => (1, (&*lists, &*order), &[][..]), + Job::Joined(_, lists, order, parts, signals) => (1 + parts.len(), (&*lists, &*order), &signals[..]), + _ => return Err(next), + }; + let hosts = || lists.1.iter().map(|&i| lists.0[i].host()); + match &next { + Job::Value(wait) => { + let met = wait.met() + || crate::host::late_met_known(wait) == Some(true) + || hosts().any(|list| crate::host::will_meet(list, wait)); + if !met { + return Err(next); + } + } + &Job::Wait(fence, value) => { + if crate::fence::completed(fence as This) < value && !signals.iter().any(|&(f, v)| f == fence && v >= value) { + return Err(next); + } + } + Job::Signal(..) => {} + Job::Run(_, more, order) => { + let runs: Vec<&crate::host::HostList> = order.iter().map(|&i| more[i].host()).collect(); + if count >= most || lists.1.len() + runs.len() > most_lists || !crate::host::joinable(hosts(), &runs) { + return Err(next); + } + } + Job::Joined(..) | Job::Present(..) => return Err(next), + } + let taken = std::mem::replace(self, Job::Wait(0, 0)); + let (queue, mut lists, mut order, mut parts, mut signals) = match taken { + Job::Run(queue, lists, order) => (queue, lists, order, Vec::new(), Vec::new()), + Job::Joined(queue, lists, order, parts, signals) => (queue, lists, order, parts, signals), + other => { + *self = other; + return Err(next); + } + }; + let run = matches!(next, Job::Run(..)); + match next { + Job::Run(_, more, then) => { + parts.push(order.len()); + order.extend(then.into_iter().map(|i| i + lists.len())); + lists.extend(more); + STATS[JOINED].fetch_add(1, Relaxed); + } + Job::Signal(fence, value) => signals.push((fence, value)), + _ => {} + } + *self = Job::Joined(queue, lists, order, parts, signals); + Ok(run) } fn go(self, forced: bool) { let began = Instant::now(); let _doing = crate::timeline::span(match self { Job::Run(..) => "the line: a submission", + Job::Joined(..) => "the line: submissions joined", Job::Present(..) => "the line: a present", Job::Signal(..) => "the line: a signal", _ => "the line: a wait that is met", @@ -365,6 +457,24 @@ impl Work for Job { } QUEUED.fetch_sub(1, Relaxed); } + Job::Joined(queue, lists, order, parts, signals) => { + let _ = queue; + #[cfg(feature = "diagnostics")] + crate::capture::op(queue, || { + format!("RUN {} parts of submissions in one, {} lists (its thread's)", 1 + parts.len(), order.len()) + }); + match crate::host::host() { + Some(host) => host.execute_parts(lists, order, &parts), + None => drop(lists), + } + // (A part that had no list is one all the same.) + QUEUED.fetch_sub(1 + parts.len() as u64, Relaxed); + for (fence, value) in signals { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + } Job::Signal(fence, value) => { if !crate::host::late_signal(fence, value) { crate::fence::set(fence as This, value); @@ -392,7 +502,7 @@ static QUEUED: AtomicU64 = AtomicU64::new(0); /// threads of the title waited, in microseconds, for room in the line, at a /// present, and for a drain, and the drains; what our thread worked; waits /// not met at a present. -static STATS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; +static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; const RUNS: usize = 0; const PRESENTS: usize = 1; const DEPTH: usize = 2; @@ -403,6 +513,8 @@ const DRAINING: usize = 6; const DRAINS: usize = 7; const BUSY: usize = 8; const FORCED: usize = 9; +/// Parts prepared together with the one before them. +const JOINED: usize = 10; /// How many submissions may be in the line when a submit call returns /// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's). @@ -593,7 +705,8 @@ pub(super) fn line(frames: f64) { tracing::info!( "submissions prepared by a thread of ours, per frame (VICTORY_ASYNC_SUBMIT): {:.1} in {:.1} presents, {:.1} in the line \ when one was added (at most {:.0}); that thread worked {:.1} ms; threads of the title waited {:.1} ms for room in the \ - line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}", + line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}; {:.1} of the \ + submissions were prepared together with the one before them (VICTORY_JOIN_PARTS)", s[RUNS] / frames, s[PRESENTS] / frames, s[DEPTH] / s[RUNS].max(1.0), @@ -603,7 +716,8 @@ pub(super) fn line(frames: f64) { ms(AT_PRESENT), ms(DRAINING), s[DRAINS] / frames, - s[FORCED] / frames + s[FORCED] / frames, + s[JOINED] / frames ); } @@ -623,6 +737,8 @@ mod tests { Slow(&'static str, Log, Arc<(Mutex, Condvar)>), Signal(usize, u64, Log), Present(&'static str, Log), + /// Takes others of its kind, waits that are met, and signals along. + Group(Vec<&'static str>, Log, Vec<(usize, u64)>), } impl Work for T { @@ -640,7 +756,24 @@ mod tests { matches!(self, T::Present(..)) } fn runs(&self) -> bool { - matches!(self, T::Run(..) | T::Slow(..)) + matches!(self, T::Run(..) | T::Slow(..) | T::Group(..)) + } + fn take_along(&mut self, next: T) -> Result { + let T::Group(names, _, signals) = self else { + return Err(next); + }; + match next { + T::Group(more, ..) if names.len() < 3 => { + names.extend(more); + Ok(true) + } + T::Wait(f, v) if crate::fence::completed(f as This) >= v || signals.contains(&(f, v)) => Ok(false), + T::Signal(f, v, _) => { + signals.push((f, v)); + Ok(false) + } + other => Err(other), + } } fn go(self, forced: bool) { match self { @@ -661,6 +794,12 @@ mod tests { log.lock().unwrap().push(format!("signal {value}")); crate::fence::set(fence as This, value); } + T::Group(names, log, signals) => { + log.lock().unwrap().push(names.join("+")); + for (fence, value) in signals { + crate::fence::set(fence as This, value); + } + } } } } @@ -706,6 +845,34 @@ mod tests { assert!(done); } + /// A submission takes what follows it in its queue along, up to what it + /// cannot take, which stays at its place; the counts come out even. + #[test] + fn submissions_take_those_behind_them_along() { + let lane = Lane::new(); + let log: Log = Default::default(); + let f = fence(); + let part = |name| T::Group(vec![name], log.clone(), Vec::new()); + lane.push(1, [part("a"), T::Wait(f, 0), part("b")]); + lane.push(2, [part("other queue"), T::Wait(f, 1), part("behind a's signal")]); + lane.push(1, [T::Signal(f, 1, log.clone()), T::Wait(f, 1), part("c"), part("d")]); + lane.push(1, [T::Wait(f, 9), part("held"), T::Present("present", log.clone()), part("next frame")]); + // What came after the look was asked for is not touched. + let limit = lane.lock().next; + lane.push(1, [part("later")]); + lane.look(limit); + assert_eq!( + *log.lock().unwrap(), + ["a+b+c", "other queue+behind a's signal", "d", "held", "present", "next frame"], + "{:?}", + lane.lock().items.len() + ); + look(&lane); + assert_eq!(log.lock().unwrap().last().unwrap(), "later"); + let state = lane.lock(); + assert_eq!((state.presents, state.runs, state.items.len()), (0, 0, 0)); + } + /// A wait that nothing meets holds its queue until a present, which /// comes behind everything given before it and before what comes after. #[test] From 7bc7c0748dcbc35cf95d156faac9c8f8831210e9 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:36:09 -0600 Subject: [PATCH 11/31] Write faults: a block just written rests before it is guarded again (VICTORY_GUARD_REST=0: not), a fault opens the view it came through alone (VICTORY_OPEN_ONE_VIEW=0: every view), guarded blocks kept as bits A book of the faults (VICTORY_FAULT_BOOK=, diagnostics) says of the dorm: 586 faults a frame on 900 blocks, 245 of them on a block that had faulted in the same frame already, 220 within 3 ms of the refresh that made the block read-only; 69 ms a frame of the title's threads, of which 6 with the guards' lock and 63 waiting for it. What is held under it is mostly VirtualProtect (5 us and more in the game's process, one at a time whoever asks: a bench found 14 threads no faster than one). - A block a write fault opened is left open by the refreshes of the next 3 ms and told as written at each. - The other views of its page stay read-only, not clean. - The sets of guarded, clean, absent and aliased blocks are bits, a range is looked at by words; the lock is let go between the runs a refresh guards; a fault that finds its block open takes no lock; the record of the title's views is read by many threads at once; the kernel is not asked about memory known to be a guarded view. Run faults-2 (A/B of both switches, 20 phases of 10 s in the dorm): faults 601 -> 391 a frame, blocks made read-only 928 -> 407, the title's threads 27.5 -> 15.8 ms a frame in them (69 before), frame 64.8 -> 62.5 ms. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/faultbook.rs | 110 ++++++ crates/victory-gpu/src/inplace.rs | 33 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/queue.rs | 1 + crates/victory-gpu/src/shadow.rs | 3 +- crates/victory-gpu/src/watch.rs | 543 ++++++++++++++++++++++------ 6 files changed, 569 insertions(+), 123 deletions(-) create mode 100644 crates/victory-gpu/src/faultbook.rs diff --git a/crates/victory-gpu/src/faultbook.rs b/crates/victory-gpu/src/faultbook.rs new file mode 100644 index 0000000..9fca8fa --- /dev/null +++ b/crates/victory-gpu/src/faultbook.rs @@ -0,0 +1,110 @@ +//! A book of the title's write faults on guarded view memory +//! (`VICTORY_FAULT_BOOK=`; builds with diagnostics): which block, when +//! in the frame, what it waited for, and what else happened to the block +//! (taken by a refresh, asked about), for 40 frames from each of the times +//! `VICTORY_FAULT_BOOK_AT` gives (seconds after the start; 150,210,270 unless +//! given). Written as `..bin`, records of 40 bytes: ticks of the +//! performance counter, two words, thread, what. +#![cfg(feature = "diagnostics")] + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; + +/// What a record is of. +#[derive(Clone, Copy)] +#[repr(u32)] +pub(crate) enum What { + /// A frame ended (a: its number). + Frame = 0, + /// A write fault opened block `a`; b: blocks opened with it (the upper + /// 32 bits), nanoseconds of waiting for the guards' lock; c: nanoseconds + /// with it. + Fault = 1, + /// Blocks `[a, b)` were found written, or never taken, and made read-only. + Taken = 2, + /// `[a, b)` was asked about and known unwritten by its bits. + Known = 3, + /// `[a, b)` was asked about block by block; c: how many were written. + Asked = 4, + /// We opened block `a` ourselves. + Ours = 5, + /// Another view of a page taken, block `a`, was made read-only. + Alias = 6, + /// A fault on block `a` that someone else had opened; b: nanoseconds. + Open = 7, + /// Blocks `[a, b)` were opened ahead of the title's writes. + Ahead = 8, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Record { + at: i64, + a: u64, + b: u64, + c: u64, + thread: u32, + what: u32, +} + +static ON: AtomicBool = AtomicBool::new(false); +static BOOK: Mutex> = Mutex::new(Vec::new()); + +fn ticks() -> i64 { + let mut t = 0; + // SAFETY: an out pointer of the right size. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut t) }; + t +} + +/// Whether records are kept now. +pub(crate) fn on() -> bool { + ON.load(Relaxed) +} + +pub(crate) fn note(what: What, a: usize, b: usize, c: u64) { + if !on() { + return; + } + // SAFETY: a question about this thread. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let record = Record { at: ticks(), a: a as u64, b: b as u64, c, thread, what: what as u32 }; + BOOK.lock().unwrap_or_else(|e| e.into_inner()).push(record); +} + +/// A frame ended. +pub(crate) fn frame() { + const FRAMES: u64 = 40; + static SETTINGS: OnceLock)>> = OnceLock::new(); + static BEGAN: OnceLock = OnceLock::new(); + static LEFT: AtomicU64 = AtomicU64::new(0); + static MADE: AtomicU64 = AtomicU64::new(0); + let began = *BEGAN.get_or_init(std::time::Instant::now); + let Some((file, times)) = SETTINGS.get_or_init(|| { + let file = std::env::var("VICTORY_FAULT_BOOK").ok().filter(|f| !f.is_empty())?; + let times = std::env::var("VICTORY_FAULT_BOOK_AT").unwrap_or_else(|_| "150,210,270".into()); + Some((file, times.split(',').filter_map(|t| t.trim().parse().ok()).collect())) + }) else { + return; + }; + note(What::Frame, crate::frame::current() as usize, 0, 0); + if on() { + if LEFT.fetch_sub(1, Relaxed) > 1 { + return; + } + ON.store(false, Relaxed); + let records = std::mem::take(&mut *BOOK.lock().unwrap_or_else(|e| e.into_inner())); + let file = format!("{file}.{}.bin", MADE.fetch_add(1, Relaxed)); + std::thread::spawn(move || { + // SAFETY: plain data, every byte of it written. + let bytes = unsafe { std::slice::from_raw_parts(records.as_ptr().cast::(), size_of_val(&records[..])) }; + match std::fs::write(&file, bytes) { + Ok(()) => tracing::info!(file, records = records.len(), "book of faults written"), + Err(e) => tracing::warn!(file, %e, "book of faults not written"), + } + }); + } else if times.get(MADE.load(Relaxed) as usize).is_some_and(|&t| began.elapsed().as_secs() >= t) { + LEFT.store(FRAMES, Relaxed); + ON.store(true, Relaxed); + } +} diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 82275c9..8679e68 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -37,7 +37,6 @@ use std::collections::BTreeMap; use std::ffi::c_void; -use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use windows::Win32::Foundation::HANDLE; @@ -281,7 +280,9 @@ struct Views { whole: Vec<(usize, usize)>, } -static VIEWS: Mutex = Mutex::new(Views { +/// Read by many threads at once (write faults, landings), changed when the +/// runtime maps or unmaps. +static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), pages_twice: 0, @@ -289,14 +290,18 @@ static VIEWS: Mutex = Mutex::new(Views { whole: Vec::new(), }); -fn views() -> std::sync::MutexGuard<'static, Views> { - VIEWS.lock().unwrap_or_else(|e| e.into_inner()) +fn views() -> std::sync::RwLockReadGuard<'static, Views> { + VIEWS.read().unwrap_or_else(|e| e.into_inner()) +} + +fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> { + VIEWS.write().unwrap_or_else(|e| e.into_inner()) } /// The runtime made a section of `bytes` for physical pages; `committed` /// if with `SEC_COMMIT` (only such a section can be opened as a heap). pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { - let mut v = views(); + let mut v = views_mut(); v.sections.retain(|s| s.0 != section); // A handle's number given out again: the view was of the section that // had it before (it stays mapped: someone may be writing through it). @@ -308,7 +313,7 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { /// sees is of it any more, and [`beside`]'s view goes. pub fn title_memory_section_gone(section: usize) { let whole = { - let mut v = views(); + let mut v = views_mut(); let at = v.whole.iter().position(|w| w.0 == section); at.map(|i| v.whole.swap_remove(i).1) }; @@ -324,7 +329,7 @@ pub fn title_memory_section_gone(section: usize) { /// `offset` on. Call after [`crate::title_memory_remapped`] of the range. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { { - let mut v = views(); + let mut v = views_mut(); v.views.insert(at, (len, section, offset)); for k in 0..len.div_ceil(K64) { let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default(); @@ -343,7 +348,7 @@ pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { /// the views that touch it are forgotten (the runtime tells again those it /// maps anew). pub(crate) fn views_gone(at: usize, len: usize) { - let mut v = views(); + let mut v = views_mut(); if v.views.is_empty() { return; } @@ -529,7 +534,17 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover { /// `crate::watch::title_memory_reading`: until it lets go the title sees /// the same pages at `at`. pub(crate) fn beside(at: usize, len: usize) -> Option { - let mut v = views(); + let known = { + let v = views(); + let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { + return None; + }; + v.whole.iter().find(|w| w.0 == section).map(|w| (w.1, offset)) + }; + if let Some((base, offset)) = known { + return (base != 0).then(|| base + offset as usize); + } + let mut v = views_mut(); let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { return None; }; diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 29947a7..1147880 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -20,6 +20,8 @@ mod capture; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; +#[cfg(all(windows, feature = "diagnostics"))] +mod faultbook; #[cfg(windows)] mod cores; pub mod descriptor; diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 90ec3d8..6158751 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -963,6 +963,7 @@ extern "system" fn present( #[cfg(all(windows, feature = "diagnostics"))] fn frame_ends() { crate::timeline::presented(); + crate::faultbook::frame(); crate::ab::presented(|switch, was, will| { if switch == "VICTORY_ASYNC_SUBMIT" && was && !will { behind::leave(); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 671d6d8..ce94da1 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3485,7 +3485,8 @@ impl Shadow { fn update_free(&self, from: usize, to: usize) -> usize { if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { if let Some((now, written)) = crate::watch::writes(from, to, true) { - let guarded = crate::watch::guarded(from, to); + // (A range whose blocks rest after a write has no guard now.) + let guarded = crate::watch::guarded(from, to) || self.watched.load(Ordering::Relaxed) == GUARDED; self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); self.refresh_check(from, to); diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 92c69e5..7d98205 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -27,6 +27,7 @@ //! before. use std::collections::{BTreeMap, BTreeSet}; +use std::ops::{Bound, RangeBounds}; use std::sync::{Condvar, Mutex, RwLock}; /// The unit tracked and copied: 64 KiB, the console's page (the kernel's @@ -625,7 +626,10 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve // Read-only since an asking noted it: the bits first, then the journal. if guarded && published(start, end) { #[cfg(feature = "diagnostics")] - tally(2, 1); + { + tally(2, 1); + crate::faultbook::note(crate::faultbook::What::Known, first, last, 0); + } let j = journal(); return Some((next_asking(), of(&j))); } @@ -636,7 +640,9 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve return Some(known); } let mut guards_asked = false; - let pages = match kernel_written(first, last) { + // (View memory read-only by our hand: the kernel would refuse.) + let refused = guarded && light() && PROTECTED.any(first, last); + let pages = match if refused { None } else { kernel_written(first, last) } { Some(pages) => pages, None => { guards_asked = true; @@ -692,6 +698,10 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], let (first, last) = (start / PAGE, end.div_ceil(PAGE)); // The bits first, then the journal, as in `writes`. let known = published(start, end); + #[cfg(feature = "diagnostics")] + if known { + crate::faultbook::note(crate::faultbook::What::Known, first, last, 1); + } let j = journal(); if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { return false; @@ -877,7 +887,7 @@ static PROTECTED: Bits = Bits::new(); 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) { PUBLISHED.set(*page); } } @@ -948,9 +958,9 @@ pub fn title_memory_allocated(at: usize, len: usize) { return; } let mut g = guards(); - let blocks: Vec = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + let blocks: Vec = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).collect(); for block in blocks { - g.held.remove(&block); + g.held.remove(block); PUBLISHED.clear(block); } } @@ -967,7 +977,7 @@ pub(crate) fn look_at_holes() { let blocks: Vec = { let g = guards(); let from = FROM.load(std::sync::atomic::Ordering::Relaxed); - let part: Vec = g.held.range(from..).take(g.held.len() / PARTS + 1).copied().collect(); + let part: Vec = g.held.range(from..).take(g.held.len() / PARTS + 1).collect(); FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed); part }; @@ -980,7 +990,7 @@ pub(crate) fn look_at_holes() { // (Or unmapped memory was mapped since the part was taken: told // already, and forgotten.) let mut g = guards(); - if g.held.remove(&block) { + if g.held.remove(block) { PUBLISHED.clear(block); static SAID: std::sync::Once = std::sync::Once::new(); SAID.call_once(|| { @@ -1037,16 +1047,162 @@ fn guards_timed() -> std::sync::MutexGuard<'static, Guards> { g } +/// A set of blocks, a bit each: a fault, or a look at a range of thousands of +/// blocks, is a few words of it and no walk through a tree of every guarded +/// block there is. +struct Blocks(BTreeMap>); + +impl Blocks { + /// The words of 4 GiB. + const WORDS: usize = 1 << 10; + const IN_PIECE: usize = Blocks::WORDS * 64; + + const fn new() -> Blocks { + Blocks(BTreeMap::new()) + } + + fn word(&self, word: usize) -> u64 { + self.0.get(&(word / Blocks::WORDS)).map_or(0, |piece| piece[word % Blocks::WORDS]) + } + + fn contains(&self, block: usize) -> bool { + self.word(block / 64) >> (block % 64) & 1 != 0 + } + + /// Whether it was not there. + fn insert(&mut self, block: usize) -> bool { + let piece = self.0.entry(block / Blocks::IN_PIECE).or_insert_with(|| Box::new([0; Blocks::WORDS])); + let word = &mut piece[block % Blocks::IN_PIECE / 64]; + let was = *word; + *word |= 1 << (block % 64); + was != *word + } + + /// Whether it was there. + fn remove(&mut self, block: usize) -> bool { + let Some(piece) = self.0.get_mut(&(block / Blocks::IN_PIECE)) else { + return false; + }; + let word = &mut piece[block % Blocks::IN_PIECE / 64]; + let was = *word; + *word &= !(1 << (block % 64)); + was != *word + } + + fn insert_all(&mut self, blocks: std::ops::Range) { + for block in blocks { + self.insert(block); + } + } + + /// Those of `range`, in order. + fn range(&self, range: impl RangeBounds) -> impl Iterator + '_ { + let first = match range.start_bound() { + Bound::Included(&first) => first, + Bound::Excluded(&before) => before.saturating_add(1), + Bound::Unbounded => 0, + }; + // (Exclusive. No block's number is near the top.) + let last = match range.end_bound() { + Bound::Included(&last) => last.saturating_add(1), + Bound::Excluded(&last) => last, + Bound::Unbounded => usize::MAX, + } + .max(first); + self.0.range(first / Blocks::IN_PIECE..=last / Blocks::IN_PIECE).flat_map(move |(&piece, words)| { + let base = piece * Blocks::IN_PIECE; + let from = first.max(base) - base; + let to = last.min(base + Blocks::IN_PIECE).saturating_sub(base); + let words = if from < to { &words[from / 64..to.div_ceil(64)] } else { &[][..] }; + words.iter().enumerate().flat_map(move |(k, &bits)| { + let at = (from / 64 + k) * 64; + BitsOf(bits & in_word(at, from, to)).map(move |bit| base + at + bit) + }) + }) + } + + fn len(&self) -> usize { + self.0.values().flat_map(|piece| piece.iter()).map(|word| word.count_ones() as usize).sum() + } +} + +/// Of the 64 blocks from `at` on, those in `[from, to)`, a bit each. +fn in_word(at: usize, from: usize, to: usize) -> u64 { + let low = from.saturating_sub(at).min(64); + let high = to.saturating_sub(at).min(64); + if low >= high { 0 } else { (u64::MAX >> (64 - (high - low))) << low } +} + +/// The bits of a word that are set, by number. +struct BitsOf(u64); + +impl Iterator for BitsOf { + type Item = usize; + fn next(&mut self) -> Option { + let bit = (self.0 != 0).then(|| self.0.trailing_zeros() as usize)?; + self.0 &= self.0 - 1; + Some(bit) + } +} + +/// Whether a write fault opens the view that was written and leaves the +/// page's other views read-only, not clean any more +/// (`VICTORY_OPEN_ONE_VIEW=0`: opens them all, as before). +/// +/// The others were opened (a change of protection each, under the guards' +/// lock, with other faults waiting) and made read-only again when the page +/// was next taken, though the title writes through one of them: 586 faults a +/// frame opened 880 blocks (run faults-1). A write through one left as it was +/// faults, and opens it. +fn open_one_view() -> bool { + crate::toggled!("VICTORY_OPEN_ONE_VIEW") +} + +/// How long a block the title has just opened by a write is left open by +/// those that take it (`VICTORY_GUARD_REST=`, 3,000 unless +/// given; `0`: not at all, as before). +/// +/// 220 of a frame's 586 faults came within 3 ms after a refresh had taken the +/// block and made it read-only, while the title was still writing it, and +/// what a refresh takes is asked about again by the next within a millisecond +/// (run faults-1): made read-only, written, opened, up to a dozen times a +/// frame. A block that rests counts as written at each asking, so nothing is +/// missed; it is read-only at the first asking after its rest, which the +/// title's later writes are seen by. +fn rest() -> std::time::Duration { + #[cfg(test)] + { + REST_IN_TEST.get() + } + #[cfg(not(test))] + { + static US: std::sync::OnceLock = std::sync::OnceLock::new(); + if !crate::toggled!("VICTORY_GUARD_REST") { + return std::time::Duration::ZERO; + } + let us = *US.get_or_init(|| { + std::env::var("VICTORY_GUARD_REST").ok().and_then(|v| v.trim().parse().ok()).filter(|us| *us > 1).unwrap_or(3000) + }); + std::time::Duration::from_micros(us) + } +} + +#[cfg(test)] +thread_local! { + /// [`rest`], for what this thread asks. + static REST_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(std::time::Duration::ZERO) }; +} + struct Guards { /// Blocks we made read-only. - protected: BTreeSet, + protected: Blocks, /// Of those, the ones not written since a copy took them. - clean: BTreeSet, + clean: Blocks, /// Blocks already copied as zeros. While they remain wholly uncommitted, /// the copy can skip hundreds of MB of failing kernel reads per world frame. - absent: BTreeSet, + absent: Blocks, /// Of those, the ones in placeholders ([`known_holes`]). - held: BTreeSet, + held: Blocks, /// Blocks that were absent and turned out to be other memory than views /// when something was there again: never guarded, copied every time. foreign: BTreeSet, @@ -1060,24 +1216,44 @@ struct Guards { /// read-only together with those (which are in it as well): what opens /// one opens them all. (A write's range can be huge, `fread`'s, so only /// these are looked up.) - aliased: BTreeSet, + aliased: Blocks, + /// Blocks opened by a write fault, and when ([`rest`]). + opened: std::collections::HashMap>, } impl Guards { fn left_alone(&self, block: usize) -> bool { self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block)) } + + /// Whether `block` is left open for now: the title has just written it. + fn rests(&self, block: usize, rest: std::time::Duration) -> bool { + !rest.is_zero() && self.opened.get(&block).is_some_and(|at| at.elapsed() < rest) + } + + /// A write fault opened `block`. + fn opened(&mut self, block: usize) { + const MANY: usize = 1 << 13; + if self.opened.len() >= MANY { + self.opened.retain(|_, at| at.elapsed().as_millis() < 50); + if self.opened.len() >= MANY { + self.opened.clear(); + } + } + self.opened.insert(block, std::time::Instant::now()); + } } static GUARDS: Mutex = Mutex::new(Guards { - protected: BTreeSet::new(), - clean: BTreeSet::new(), - absent: BTreeSet::new(), - held: BTreeSet::new(), + protected: Blocks::new(), + clean: Blocks::new(), + absent: Blocks::new(), + held: Blocks::new(), foreign: BTreeSet::new(), kernel: Vec::new(), changing: Vec::new(), - aliased: BTreeSet::new(), + aliased: Blocks::new(), + opened: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -1227,7 +1403,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { } let g = guards(); (at / BLOCK..=(at + len - 1) / BLOCK) - .all(|b| !g.clean.contains(&b) && !g.absent.contains(&b) && !g.protected.contains(&b)) + .all(|b| !g.clean.contains(b) && !g.absent.contains(b) && !g.protected.contains(b)) } /// For view memory: the pages of `[start, end)`'s blocks written since @@ -1246,7 +1422,7 @@ fn guard(start: usize, end: usize) -> Option> { let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && (PROTECTED.any(first, first + 1) || { let g = guards_timed(); - g.protected.contains(&first) || g.absent.contains(&first) + g.protected.contains(first) || g.absent.contains(first) }); if !known && !is_view(start, end) { return None; @@ -1264,7 +1440,7 @@ fn guard(start: usize, end: usize) -> Option> { tally(3, 1); return Some(Vec::new()); } - g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect() + g.absent.range(first..last).filter(|block| !g.held.contains(*block)).collect() }; let mut came: Vec<(usize, bool)> = Vec::new(); let mut uncommitted_until = first; @@ -1281,45 +1457,56 @@ fn guard(start: usize, end: usize) -> Option> { came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK))); } } + let rest = rest(); let mut g = guards_timed(); #[cfg(feature = "diagnostics")] tally(4, 1); for &(block, view) in &came { - if g.absent.remove(&block) && !view { + if g.absent.remove(block) && !view { g.foreign.insert(block); } } + // The range's blocks that are neither clean nor known to be holes. A + // frame asks about some 10 GB of view memory, 150,000 blocks, nearly all + // clean. let mut written = Vec::new(); - let mut run: Option = None; - // The range's clean blocks, and those known to be holes, in order: read - // off the sets in one pass, not looked up one block at a time. A frame - // asks about some 10 GB of view memory, 150,000 blocks, nearly all - // clean: the lookups were most of the 60-90 ms a frame of "guards" - // (run 54). What the loop adds to the sets meanwhile is the block it - // stands at or ones before it. - let clean: Vec = g.clean.range(first..last).copied().collect(); - let absent: Vec = g.absent.range(first..last).copied().collect(); - let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable()); - for block in first..=last { - let is_clean = clean.next_if_eq(&block).is_some(); - let is_absent = absent.next_if_eq(&block).is_some(); - if block < last && !is_clean && !is_absent { - written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); - if g.protected.contains(&block) { - // Read-only by way of another view of its page, or not clean - // because one could not be made so. - if cover(&mut g, block, block + 1) { - g.clean.insert(block); - } - } else if !g.foreign.contains(&block) && !g.left_alone(block) { - run.get_or_insert(block); - continue; - } + for word in first / 64..last.div_ceil(64) { + let known = g.clean.word(word) | g.absent.word(word); + written.extend(BitsOf(!known & in_word(word * 64, first, last)).map(|bit| word * 64 + bit)); + } + let mut run: Option<(usize, usize)> = None; + for &block in &written { + if let Some((from, to)) = run + && to != block + { + protect(&mut g, from, to); + run = None; + // Faults of the title's wait for the lock: each block is done on + // its own, and looked at anew below. + drop(g); + g = guards_timed(); } - if let Some(from) = run.take() { - protect(&mut g, from, block); + if g.protected.contains(block) { + // Read-only by way of another view of its page, or not clean + // because one could not be made so. + if let Some((from, to)) = run.take() { + protect(&mut g, from, to); + } + if cover(&mut g, block, block + 1) { + g.clean.insert(block); + } + } 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(&mut g, from, to); } } + if let Some((from, to)) = run { + protect(&mut g, from, to); + } + drop(g); + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Asked, first, last, written.len() as u64); Some(written) } @@ -1374,6 +1561,8 @@ fn is_view(start: usize, end: usize) -> bool { /// one of those is this memory written, and only a fault can say so. /// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before. fn protect(g: &mut Guards, from: usize, to: usize) { + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Taken, from, to, 0); protect_here(g, from, to); cover(g, from, to); } @@ -1403,7 +1592,7 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { let mut all = true; for (page, others) in elsewhere(from * BLOCK, (to - from) * BLOCK) { let block = page / BLOCK; - if !g.protected.contains(&block) { + if !g.protected.contains(block) { continue; // not there, or not ours to guard } #[cfg(feature = "diagnostics")] @@ -1415,7 +1604,7 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { } if !covered { all = false; - g.clean.remove(&block); + g.clean.remove(block); } } all @@ -1430,10 +1619,10 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { fn protect_alias(g: &mut Guards, block: usize) -> bool { use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; g.aliased.insert(block); - if g.protected.contains(&block) { + if g.protected.contains(block) { return true; } - if g.left_alone(block) { + if g.left_alone(block) || g.rests(block, rest()) { return false; } // Ahead of the protection. @@ -1450,6 +1639,8 @@ fn protect_alias(g: &mut Guards, block: usize) -> bool { } if done && matches!(old, PAGE_READWRITE | PAGE_READONLY) { g.protected.insert(block); + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Alias, block, 0, 0); return true; } if done { @@ -1492,8 +1683,8 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) { done }; let note = |g: &mut Guards, from: usize, to: usize| { - g.protected.extend(from..to); - g.clean.extend(from..to); + g.protected.insert_all(from..to); + g.clean.insert_all(from..to); }; // Ahead of the protection (`PROTECTED`). (from..to).for_each(|block| PROTECTED.set(block)); @@ -1540,25 +1731,33 @@ fn uncommitted_end(block: usize) -> usize { } /// Gives write access back to the guarded blocks of `[start, end)` and -/// notes them written; true if any was guarded. The same physical pages at -/// every other view of them are opened too: the write that faulted (or is -/// ours, `crate::host::copy_mapped`) goes through one view, and every -/// guard over the pages must copy them again. -fn open(g: &mut Guards, start: usize, end: usize) -> bool { +/// notes them written; how many there were. The same physical pages at +/// every other view of them are written by that too (the write that faulted, +/// or is ours, `crate::host::copy_mapped`, goes through one view): they are +/// clean no longer, whether they are opened as well ([`open_one_view`]) or +/// not. +fn open(g: &mut Guards, start: usize, end: usize) -> usize { let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); if first >= last { - return false; + return 0; } - let mut blocks: Vec = g.protected.range(first..last).copied().collect(); + let mut blocks: Vec = g.protected.range(first..last).collect(); let here = blocks.len(); - if !g.aliased.is_empty() { - let aliased: Vec = g.aliased.range(first..last).copied().collect(); + let aliased: Vec = g.aliased.range(first..last).collect(); + if !aliased.is_empty() { + let one = open_one_view(); for block in aliased { - g.aliased.remove(&block); + g.aliased.remove(block); for other in crate::inplace::pages_of(block * BLOCK) { let other = other / BLOCK; - g.aliased.remove(&other); - if !(first..last).contains(&other) && g.protected.contains(&other) { + if one { + // Before the first can be written. + g.clean.remove(other); + PUBLISHED.clear(other); + continue; + } + g.aliased.remove(other); + if !(first..last).contains(&other) && g.protected.contains(other) { blocks.push(other); } } @@ -1567,7 +1766,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { ALIASES[1].fetch_add((blocks.len() - here) as u64, std::sync::atomic::Ordering::Relaxed); } unguard(g, &blocks); - here != 0 + here } /// Gives write access back to `blocks`, guarded ones. @@ -1577,10 +1776,10 @@ fn unguard(g: &mut Guards, blocks: &[usize]) { let started = std::time::Instant::now(); // All of them before the first can be written: a write through one is a // write of the others' bytes. - for block in blocks { + for &block in blocks { g.protected.remove(block); g.clean.remove(block); - PUBLISHED.clear(*block); + PUBLISHED.clear(block); } for &block in blocks { let mut old = 0; @@ -1611,11 +1810,13 @@ pub fn writing(at: usize, len: usize) { let last = at.saturating_add(len).div_ceil(BLOCK); if !light() || PROTECTED.any(at / BLOCK, last) { let mut g = guards_timed(); + let opened = open(&mut g, at, at.saturating_add(len)); #[cfg(feature = "diagnostics")] - let held = g.protected.len(); - open(&mut g, at, at.saturating_add(len)); - #[cfg(feature = "diagnostics")] - tally(6, (held - g.protected.len()) as u64); + { + tally(6, opened as u64); + crate::faultbook::note(crate::faultbook::What::Ours, at / BLOCK, last, opened as u64); + } + let _ = opened; } // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); @@ -1638,10 +1839,10 @@ pub fn kernel_writing(at: usize, len: usize) -> KernelWrite { open(&mut g, at, at.saturating_add(len)); if len != 0 { // Nothing known of them stands while they are left alone. - let absent: Vec = g.absent.range(first..last).copied().collect(); + let absent: Vec = g.absent.range(first..last).collect(); for block in absent { - g.absent.remove(&block); - if g.held.remove(&block) { + g.absent.remove(block); + if g.held.remove(block) { PUBLISHED.clear(block); } } @@ -1758,7 +1959,7 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { } let mut g = guards(); for &(at, n) in &ranges { - let blocks: Vec = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).copied().collect(); + let blocks: Vec = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect(); #[cfg(feature = "diagnostics")] ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed); unguard(&mut g, &blocks); @@ -1776,6 +1977,8 @@ pub fn title_memory_splitting(at: usize, len: usize) { return; } let mut g = guards(); + // (The view itself too: the part that stays is read-only until then.) + open(&mut g, at, at.saturating_add(len)); for other in others { open(&mut g, other, other + BLOCK); if CHANGING.get().0 { @@ -1905,7 +2108,7 @@ fn came_back(at: usize, write: bool) -> bool { return readable_view(at); } // (A refresh may have guarded the page that came back.) - open(&mut guards(), at, at + 1) || writable(at) + open(&mut guards(), at, at + 1) != 0 || writable(at) }; let before = changes(); if there() || again_after_change(before, there) { @@ -2016,14 +2219,10 @@ pub fn title_memory_unmapping(at: usize, len: usize) { _ => g.changing.push((first, last)), } } - let blocks: Vec = g - .protected - .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) - .copied() - .collect(); + let blocks: Vec = g.protected.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).collect(); for block in blocks { - g.protected.remove(&block); - g.clean.remove(&block); + g.protected.remove(block); + g.clean.remove(block); PUBLISHED.clear(block); PROTECTED.clear(block); } @@ -2036,8 +2235,8 @@ pub fn title_memory_unmapping(at: usize, len: usize) { pub fn title_memory_freed(at: usize, len: usize) { let mut g = guards(); let first = at / BLOCK; - let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next()); - let Some(noted) = noted.into_iter().flatten().min().copied() else { + let noted = [g.protected.range(first..).next(), g.absent.range(first..).next(), g.foreign.range(first..).next().copied()]; + let Some(noted) = noted.into_iter().flatten().min() else { return; }; let end = if len != 0 { @@ -2048,10 +2247,10 @@ pub fn title_memory_freed(at: usize, len: usize) { if noted >= end { return; } - let absent: Vec = g.absent.range(first..end).copied().collect(); + let absent: Vec = g.absent.range(first..end).collect(); for block in absent { - g.absent.remove(&block); - if g.held.remove(&block) { + g.absent.remove(block); + if g.held.remove(block) { PUBLISHED.clear(block); } } @@ -2096,10 +2295,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); - let absent: Vec = g.absent.range(range.clone()).copied().collect(); + let absent: Vec = g.absent.range(range.clone()).collect(); for block in absent { - g.absent.remove(&block); - if g.held.remove(&block) { + g.absent.remove(block); + if g.held.remove(block) { PUBLISHED.clear(block); } } @@ -2107,9 +2306,9 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, for block in foreign { g.foreign.remove(&block); } - let aliased: Vec = g.aliased.range(range).copied().collect(); + let aliased: Vec = g.aliased.range(range).collect(); for block in aliased { - g.aliased.remove(&block); + g.aliased.remove(block); } g } @@ -2153,20 +2352,41 @@ pub(crate) fn install() { }; } let at = r.ExceptionInformation[1]; - // Held across both checks: another thread may have opened the block - // since this one faulted, and a copy may have guarded it again since - // (then it is ours again, not read-only for some other reason). - let mut g = guards(); - if open(&mut g, at, at + 1) { + let block = at / BLOCK; + // 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 + // other reason). + for _ in 0..3 { + if !PROTECTED.any(block, block + 1) && writable(at) { + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Open, block, 0, 0); + return EXCEPTION_CONTINUE_EXECUTION; + } #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::GuardFaults, 1); - return EXCEPTION_CONTINUE_EXECUTION; + let began = std::time::Instant::now(); + // (Let go again before the next look: the runtime wants the + // guards to end a change.) + let mut g = guards(); + #[cfg(feature = "diagnostics")] + let waited = began.elapsed(); + let opened = open(&mut g, at, at + 1); + if opened != 0 { + g.opened(block); + drop(g); + #[cfg(feature = "diagnostics")] + { + 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; + crate::faultbook::note(crate::faultbook::What::Fault, block, opened << 32 | ns, held); + } + return EXCEPTION_CONTINUE_EXECUTION; + } } if writable(at) { return EXCEPTION_CONTINUE_EXECUTION; } - // (The runtime wants the guards to end a change.) - drop(g); match ours { Some(exit) => fail(exit), None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION, @@ -2452,7 +2672,7 @@ mod tests { assert!(written.contains(&(p / PAGE + 1, now))); assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now)); } - assert!(!guards().held.contains(&(p / BLOCK + 1))); + assert!(!guards().held.contains(p / BLOCK + 1)); drop(writing); ask(); assert!((0..3).all(known) == holes); @@ -2460,12 +2680,12 @@ mod tests { let _changing = title_memory_remapping(); title_memory_unmapping(p, BLOCK); ask(); - assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); + assert!(!known(0) && !guards().held.contains(p / BLOCK)); } ask(); assert!((0..3).all(known) == holes); title_memory_freed(p, BLOCK); - assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); + assert!(!known(0) && !guards().held.contains(p / BLOCK)); title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our placeholders. unsafe { @@ -2495,7 +2715,7 @@ mod tests { assert!(writes(at, at + BLOCK, true).is_some()); { let g = guards(); - assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK))); + assert!(!g.protected.contains(at / BLOCK) && !g.clean.contains(at / BLOCK)); } assert!(!published(at, at + BLOCK)); // SAFETY: our view. @@ -2554,7 +2774,7 @@ mod tests { assert!(holes.iter().all(|page| written.contains(page)), "copied every time"); as_made(); let g = guards(); - assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block))); + assert!(holes.iter().all(|&block| !g.held.contains(block) && !g.absent.contains(block))); } writing(p, BLOCK); as_made(); @@ -2575,7 +2795,7 @@ mod tests { let noted = |block: usize| { let g = guards(); let block = p / BLOCK + block; - g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block) + g.protected.contains(block) || g.clean.contains(block) || g.absent.contains(block) }; assert!(guard(p, p + 3 * BLOCK).is_some()); assert!(noted(0) && noted(1) && noted(2)); @@ -3031,6 +3251,93 @@ mod tests { drop_views(section, &[one, two], SIZE); } + /// A write opens the view it goes through and no other: the others stay + /// read-only, are told as written, and take writes of their own. + #[test] + fn a_write_opens_the_view_it_goes_through() { + let (section, one, two) = two_views(BLOCK); + let page = |view: usize| view / PAGE; + for view in [one, two] { + assert_eq!(guard(view, view + BLOCK), Some(vec![page(view)])); + } + // SAFETY (all): a view, opened by the handler. + unsafe { ((two + 8) as *mut u8).write(1) }; + assert!(writable(two) && !writable(one)); + unsafe { ((one + 8) as *mut u8).write(1) }; + assert!(writable(two) && writable(one)); + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + assert_eq!(guard(two, two + BLOCK), Some(vec![page(two)])); + // Written at the view that was left as it was, after the other. + unsafe { ((two + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)]), "not clean, though never opened"); + assert!(!writable(two) && !writable(one)); + assert_eq!(guard(two, two + BLOCK), Some(vec![page(two)])); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + // Of a page that was told at one view, a kernel write to the other + // finds it open. + unsafe { ((two + 8) as *mut u8).write(1) }; + assert!(!writable(one)); + writing(one, 8); + assert!(writable(one)); + drop_views(section, &[one, two], BLOCK); + } + + /// A block the title has just written is not made read-only, and is told + /// as written at each asking, at every view of it, until it has rested. + #[test] + fn a_block_just_written_rests() { + let (section, one, two) = two_views(BLOCK); + let page = one / PAGE; + let rests = |rests: bool| REST_IN_TEST.set(std::time::Duration::from_secs(if rests { 3600 } else { 0 })); + assert_eq!(guard(one, one + BLOCK), Some(vec![page])); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + rests(true); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new()), "nothing written: as it was"); + // SAFETY (all): a view, opened by the handler. + unsafe { ((two + 8) as *mut u8).write(1) }; + for _ in 0..3 { + assert_eq!(guard(one, one + BLOCK), Some(vec![page])); + assert!(writable(two), "no fault for the next write"); + assert!(writes(two, two + BLOCK, true).is_some() && !published(two, two + BLOCK) && !published(one, one + BLOCK)); + unsafe { ((two + 8) as *mut u8).write(1) }; + } + rests(false); + assert_eq!(guard(one, one + BLOCK), Some(vec![page])); + assert!(!writable(two) && !writable(one)); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + drop_views(section, &[one, two], BLOCK); + } + + /// The set of blocks against another of the same. + #[test] + fn blocks_are_a_set() { + let (mut set, mut other) = (Blocks::new(), BTreeSet::new()); + let mut seed = 1u64; + let mut next = |n: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for round in 0..40_000 { + // About the ends of pieces and words. + let block = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); + if next(3) == 0 { + assert_eq!(set.remove(block), other.remove(&block)); + } else { + assert_eq!(set.insert(block), other.insert(block)); + } + assert_eq!(set.contains(block), other.contains(&block)); + if round % 64 == 0 { + let a = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); + let b = a + [next(10), next(300), 2 * Blocks::IN_PIECE + next(100)][next(3)]; + assert!(set.range(a..b).eq(other.range(a..b).copied()), "{a}..{b}"); + assert!(set.range(a..).eq(other.range(a..).copied()) && set.range(..).eq(other.iter().copied())); + assert!(set.range(a..=b).eq(other.range(a..=b).copied())); + assert_eq!(set.len(), other.len()); + } + } + assert_eq!(set.range(5..usize::MAX).next(), other.range(5..).next().copied()); + } + /// What is known of a block by its bit is so at every view of its page: /// the write through one takes the bits of all. #[test] @@ -3251,7 +3558,14 @@ mod many_askers_tests { /// again between. #[test] fn no_write_to_views_is_lost_between_askers() { - writes_to_views_are_not_lost::<1>(); + writes_to_views_are_not_lost::<1>(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); } /// The same of pages shown at three addresses, each of which has copies @@ -3261,10 +3575,11 @@ 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>(); + writes_to_views_are_not_lost::<3>(0); } - fn writes_to_views_are_not_lost() { + fn writes_to_views_are_not_lost(rest: u64) { + let rest = std::time::Duration::from_micros(rest); const PAGES: usize = 12; const THREADS: usize = 8; // SAFETY: views of a section of our own. @@ -3292,6 +3607,7 @@ mod many_askers_tests { std::thread::scope(|s| { if VIEWS > 1 { s.spawn(move || { + super::REST_IN_TEST.set(rest); let mut last = [0u64; VIEWS]; for round in 0..300usize { let (page, asked) = (round * 5 % PAGES, round % VIEWS); @@ -3321,6 +3637,7 @@ mod many_askers_tests { for t in 0..THREADS { let (by_bits, past) = (&by_bits, &past); s.spawn(move || { + super::REST_IN_TEST.set(rest); let mut last = [[0u64; PAGES]; VIEWS]; let mut seed = t as u64 * 7919 + 1; let mut next = |n: usize| { From ac11bbbe5f318221fe94307828063dd6dd1b9f39 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:40:12 -0600 Subject: [PATCH 12/31] Pages are mapped by sixteen threads while the title streams as fast as they are mapped, by the caller alone otherwise (VICTORY_MAP_THREADS=auto, which it is unless set) The title's streaming thread spends 400 to 750 ms of a second in mapping calls in the world's first minute (runs stream-1 to -4; DirectStorage itself answers in 1 to 8 ms): each call waits a millisecond or two in the host's queue behind the guards' protection changes. Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/xmem.rs | 91 ++++++++++++++++++++++++-- 1 file changed, 85 insertions(+), 6 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index ad0cdb1..b34298e 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -10,7 +10,7 @@ use std::alloc::{Layout, alloc, dealloc}; use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, LazyLock, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; use windows_sys::Win32::Foundation::{ @@ -1066,6 +1066,7 @@ pub extern "system" fn XMemMapPhysicalPages( let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec()); let mut costed = Costed::begin(Some(n)); let _called = victory_gpu::timeline::span("the title's XMemMapPhysicalPages"); + let _busy = Busy::begin(); let mut physical = physical(); if let Some(costed) = &mut costed { costed.waited = costed.started.elapsed().as_nanos() as u64; @@ -1155,6 +1156,7 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( pub fn map_alias(to: u64, from: u64, len: u64) -> bool { let (to, from, len) = (to as usize, from as usize, len as usize); let _costed = Costed::begin(None); + let _busy = Busy::begin(); let mut physical = physical(); // As in `XMemMapPhysicalPages`: no read in place meets the gap. let _changing = victory_gpu::title_memory_remapping(); @@ -1194,6 +1196,7 @@ pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool { let mut ok = true; let mut at = 0; while at < pages.len() { + let _busy = Busy::begin(); let mut physical = physical(); let mut ops: Vec = Vec::new(); let mut touched = std::collections::HashSet::new(); @@ -1221,6 +1224,7 @@ fn scatter(wanted: &[(usize, usize)]) -> bool { let mut ok = true; let mut at = 0; while at < wanted.len() { + let _busy = Busy::begin(); let mut costed = Costed::begin(None); let mut ops: Vec = Vec::new(); let mut physical = physical(); @@ -1256,7 +1260,9 @@ fn scatter(wanted: &[(usize, usize)]) -> bool { const GROUP: usize = 64; /// How many threads map a group of pages side by side (`VICTORY_MAP_THREADS`; -/// 1: the caller alone, a page after the other, as before). +/// 1: the caller alone, a page after the other, as before; `auto`, which it +/// is unless set: 1 while mapping takes little of the time, [`WIDE`] while the +/// title streams as fast as its pages are mapped, [`Busy`]). /// /// Mapping and unmapping a view wait for a lock that every protection change /// of a view takes too, and our guards make 100,000 of those a second, from @@ -1269,10 +1275,74 @@ fn side_by_side() -> usize { if let Some(on) = victory_gpu::switched("VICTORY_MAP_THREADS") { return if on { 8 } else { 1 }; } - static THREADS: LazyLock = LazyLock::new(|| { - std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32) + match asked_threads() { + Some(n) => n, + None if BUSY.2.load(Ordering::Relaxed) => WIDE, + None => 1, + } +} + +/// Threads while the title streams fast: they stand in the host's queue side +/// by side, each for a millisecond or two a page in the world's first seconds. +const WIDE: usize = 16; + +/// `VICTORY_MAP_THREADS` as a number; `None`: by how much there is to map. +fn asked_threads() -> Option { + static ASKED: LazyLock> = LazyLock::new(|| { + std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).map(|n: usize| n.clamp(1, 32)) }); - *THREADS + *ASKED +} + +/// Of the window under way: when it began, the nanoseconds spent mapping in +/// it; and whether the last one was busy. +static BUSY: (Mutex>, AtomicU64, std::sync::atomic::AtomicBool) = + (Mutex::new(None), AtomicU64::new(0), std::sync::atomic::AtomicBool::new(false)); + +/// Counts the time a mapping call of the title's takes, as long as it lives. +/// More than a quarter of a window, and the calls are what loading waits for +/// (one thread of the title's makes them); less than a twentieth, they are +/// not any more. +struct Busy(std::time::Instant); + +impl Busy { + fn begin() -> Busy { + Busy(std::time::Instant::now()) + } +} + +/// Whether mapping is busy after a window of `window` with `spent` in it. +fn busy_after(was: bool, spent: std::time::Duration, window: std::time::Duration) -> bool { + spent * if was { 20 } else { 4 } > window +} + +impl Drop for Busy { + fn drop(&mut self) { + const WINDOW: std::time::Duration = std::time::Duration::from_millis(250); + let now = std::time::Instant::now(); + let all = BUSY.1.fetch_add((now - self.0).as_nanos() as u64, Ordering::Relaxed) + (now - self.0).as_nanos() as u64; + let mut began = BUSY.0.lock().unwrap_or_else(|e| e.into_inner()); + let window = now - *began.get_or_insert(self.0); + if window < WINDOW { + return; + } + *began = Some(now); + BUSY.1.store(0, Ordering::Relaxed); + let was = BUSY.2.load(Ordering::Relaxed); + let is = busy_after(was, std::time::Duration::from_nanos(all), window); + if was != is { + BUSY.2.store(is, Ordering::Relaxed); + static SAID: AtomicU64 = AtomicU64::new(0); + if asked_threads().is_none() && SAID.fetch_add(1, Ordering::Relaxed) < 200 { + tracing::info!( + "title pages are mapped by {} (VICTORY_MAP_THREADS): {:.0} ms of the last {:.0} ms went into mapping calls", + if is { "several threads" } else { "the caller alone" }, + all as f64 / 1e6, + window.as_secs_f64() * 1e3 + ); + } + } + } } /// A page of address space to unmap and, with a slice, map anew. @@ -1414,7 +1484,7 @@ mod pool { static STARTED: std::sync::Once = std::sync::Once::new(); let pool = POOL.get_or_init(|| Pool { batches: Mutex::default(), more: Condvar::new() }); STARTED.call_once(|| { - let started = (1..side_by_side()) + let started = (1..super::asked_threads().unwrap_or(super::WIDE).max(side_by_side())) .filter(|i| std::thread::Builder::new().name(format!("mapping {i}")).spawn(|| serve(pool)).is_ok()) .count(); tracing::info!(started, "threads that map pages side by side (VICTORY_MAP_THREADS=1: none)"); @@ -2415,6 +2485,15 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); } + #[test] + fn mapping_is_busy_from_a_quarter_of_the_time_to_a_twentieth() { + let ms = std::time::Duration::from_millis; + assert!(!busy_after(false, ms(60), ms(250)) && busy_after(false, ms(70), ms(250))); + assert!(busy_after(true, ms(15), ms(250)) && !busy_after(true, ms(12), ms(250))); + // A window without a call, then one short one. + assert!(!busy_after(true, ms(5), ms(4000))); + } + #[test] fn page_windows_cover_one_run_in_place() { let (a, b) = (allocate(3), allocate(1)); From 7da523a9d962c7458dfddf713645580db6b079cf Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 11:45:56 -0600 Subject: [PATCH 13/31] The stand-in for the indirect light can bound what the air scatters (VICTORY_AMBIENT_AIR, off) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/ambient.rs | 73 ++++++++++++++++++++++++++----- crates/victory-gpu/src/draw.rs | 21 ++++++--- 2 files changed, 79 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index fb45f90..8a3d46e 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -29,6 +29,10 @@ //! - `constant:`: the constant, as beloooo's fork has it. //! //! `VICTORY_AMBIENT_SHADE=,` sets the creases. +//! +//! The air of a room is lit by the same probes: without rays they hold the +//! sky's light indoors too, a brown veil at sunset. `VICTORY_AMBIENT_AIR` +//! bounds what the air scatters by a multiple of the light around. use std::sync::{Mutex, OnceLock}; @@ -44,6 +48,9 @@ pub(crate) enum Role { Resolve, /// Keeps the light visible surfaces send out. Radiance, + /// Adds the lamps' light to what the air scatters (the last program + /// that writes that volume before it is summed up along the view). + Air, } /// The program's part in this, by its name in the container. @@ -53,6 +60,8 @@ pub(crate) fn role(container: &[u8]) -> Option { Some(Role::Resolve) } else if has(b"CS_CacheScreenSpaceRadiance") { Some(Role::Radiance) + } else if has(b"CS_AccumulateLocalLightInscatteringVolume") { + Some(Role::Air) } else { None } @@ -64,6 +73,8 @@ pub(crate) fn role(container: &[u8]) -> Option { pub(crate) const LIGHT: (u8, u32) = (1, 176); pub(crate) const DEPTH: (u8, u32) = (0, 464); pub(crate) const RADIANCE: (u8, u32) = (1, 16); +/// Where the light the air scatters is. +pub(crate) const AIR: (u8, u32) = (1, 32); #[derive(Clone, Copy, PartialEq, Debug)] enum Set { @@ -91,6 +102,16 @@ pub(crate) fn on() -> bool { set() != Set::Off && !crate::pipeline::builder_runs() } +/// The most the air scatters, as a multiple of the light around +/// (`VICTORY_AMBIENT_AIR=`; unset or 0: what the title has). +fn air() -> f32 { + static SET: OnceLock = OnceLock::new(); + *SET.get_or_init(|| { + let set = std::env::var("VICTORY_AMBIENT_AIR").unwrap_or_default(); + set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(0.0) + }) +} + /// Strength and radius of the creases' shade. fn shade() -> [f32; 2] { static SET: OnceLock<[f32; 2]> = OnceLock::new(); @@ -116,7 +137,7 @@ const SOURCE: &str = r#" cbuffer Set : register(b0) { float level; float constant; float strength; float radius; float near; float tan_y; uint width; uint height; - float follow; float most; float unused0; float unused1; + float follow; float most; float air; float unused; }; Texture2D depth : register(t0); // Cells: the light they send out (then, at CELLS, the slow mean), from @@ -205,6 +226,28 @@ void gather(uint3 at : SV_DispatchThreadID) { } #endif +#ifdef AIR +RWTexture3D scattered : register(u0); +// No more than a multiple of the light around: of the room as the last +// seconds showed it, and of the surface seen in this direction (towards a +// window the air outside may be as bright as the sky is). +[RootSignature(RS)] +[numthreads(8, 8, 2)] +void clear_air(uint3 at : SV_DispatchThreadID) { + uint w, h, d; + scattered.GetDimensions(w, h, d); + if (at.x >= w || at.y >= h || at.z >= d) return; + uint2 q = min(uint2((float2(at.xy) + 0.5) / float2(w, h) * float2(PX, PY)), uint2(PX - 1, PY - 1)); + uint at0 = (q.y * PX + q.x) * 3; + float3 seen_there = float3(points[at0].w, points[at0 + 1].w, points[at0 + 2].w); + float far = float(at.z) / float(d); + float cap = air * lerp(dot(cells[CELLS].rgb, LUMA), dot(seen_there, LUMA), far); + float3 c = scattered[at]; + float has = dot(c, LUMA); + if (has > cap) scattered[at] = c * (cap / has); +} +#endif + #ifdef RAISE RWTexture2D light : register(u0); float3 unpack(uint v) { @@ -300,6 +343,7 @@ struct Pass { place: ID3D12PipelineState, gather: ID3D12PipelineState, raise: ID3D12PipelineState, + air: ID3D12PipelineState, cells: ID3D12Resource, points: ID3D12Resource, } @@ -330,6 +374,7 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) - let place = pipeline("PLACE", s!("place"))?; let gather = pipeline("GATHER", s!("gather"))?; let raise = pipeline("RAISE", s!("raise"))?; + let air = pipeline("AIR", s!("clear_air"))?; let made = |bytes| buffer(bytes).ok_or_else(windows::core::Error::empty); Ok(Pass { root: root.ok_or_else(windows::core::Error::empty)?, @@ -338,6 +383,7 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option) - place, gather, raise, + air, cells: made(CELL_BYTES)?, points: made(POINT_BYTES)?, }) @@ -370,8 +416,9 @@ pub(crate) struct Views { pub(crate) image: D3D12_GPU_DESCRIPTOR_HANDLE, /// The scene's depth, for [`Role::Resolve`]. pub(crate) depth: D3D12_GPU_DESCRIPTOR_HANDLE, - /// The size of the light's image. + /// The size of the image, and how many slices it has. pub(crate) size: [u32; 2], + pub(crate) slices: u32, } /// After the title's program of that role, in `list` with the program's view @@ -387,7 +434,10 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { Set::Estimate(level) => (level, 0.0f32), Set::Constant(level) => (0.0, level), }; - if role == Role::Resolve && constant == 0.0 && !KEPT.load(Ordering::Relaxed) { + if role != Role::Radiance && constant == 0.0 && !KEPT.load(Ordering::Relaxed) { + return false; + } + if role == Role::Air && (constant > 0.0 || air() == 0.0) { return false; } static SAID: Mutex = Mutex::new(0); @@ -410,6 +460,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[7] = views.size[1]; words[8] = 0.04f32.to_bits(); words[9] = 4.0f32.to_bits(); + words[10] = air().to_bits(); let l = &list.list; // SAFETY: an open list with the heap of the views set; the title's // program has just used both views, so their textures are in the states @@ -422,23 +473,24 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { l.SetComputeRootDescriptorTable(2, views.image); l.SetComputeRootUnorderedAccessView(3, pass.cells.GetGPUVirtualAddress()); l.SetComputeRootUnorderedAccessView(4, pass.points.GetGPUVirtualAddress()); - let run = |pso: &ID3D12PipelineState, x, y| { + let run = |pso: &ID3D12PipelineState, x, y, z| { l.SetPipelineState(pso); - l.Dispatch(x, y, 1); + l.Dispatch(x, y, z); uav_barrier(l); }; match role { Role::Radiance => { - run(&pass.keep, 8, 9); - run(&pass.mean, 1, 1); + run(&pass.keep, 8, 9, 1); + run(&pass.mean, 1, 1, 1); KEPT.store(true, Ordering::Relaxed); } + Role::Air => run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)), Role::Resolve => { if constant == 0.0 { - run(&pass.place, 8, 9); - run(&pass.gather, 20, 45); + run(&pass.place, 8, 9, 1); + run(&pass.gather, 20, 45, 1); } - run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8)); + run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); } } } @@ -463,6 +515,7 @@ mod tests { fn roles_by_name() { assert_eq!(role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), Some(Role::Resolve)); assert_eq!(role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), Some(Role::Radiance)); + assert_eq!(role(b"CS_AccumulateLocalLightInscatteringVolume_7e2f5eef"), Some(Role::Air)); assert_eq!(role(b"CS_TemporalResolve"), None); } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 4ef4340..8264a58 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2623,7 +2623,7 @@ impl State { /// The stand-in for the indirect light after a dispatch of `p` /// (`crate::ambient`). Whether it recorded anything. fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { - use crate::ambient::{DEPTH, LIGHT, RADIANCE, Role, Views}; + use crate::ambient::{AIR, DEPTH, LIGHT, RADIANCE, Role, Views}; let Some(t) = p.stages.first().map(|s| s.translated()) else { return false; }; @@ -2651,10 +2651,15 @@ impl State { let desc = unsafe { host.GetDesc() }; Some((desc, heap.gpu_handle((start + offset * 4) / 32))) }; - let image = entry(ResourceType::Uav, if role == Role::Resolve { LIGHT } else { RADIANCE }); + let at = match role { + Role::Resolve => LIGHT, + Role::Radiance => RADIANCE, + Role::Air => AIR, + }; + let image = entry(ResourceType::Uav, at); let depth = match role { Role::Resolve => entry(ResourceType::Srv, DEPTH), - Role::Radiance => image, + Role::Radiance | Role::Air => image, }; let (Some((of, image)), Some((seen, depth))) = (image, depth) else { once!(?role, "no stand-in for the indirect light: other tables"); @@ -2662,11 +2667,17 @@ impl State { }; // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) let format = if role == Role::Resolve { 42 } else { 26 }; - if of.Format.0 != format || (seen.Width, seen.Height) != (of.Width, of.Height) { + let volume = of.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if of.Format.0 != format || (seen.Width, seen.Height) != (of.Width, of.Height) || volume != (role == Role::Air) { once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image"); return false; } - crate::ambient::after(list, role, &Views { image, depth, size: [of.Width as u32, of.Height] }) + crate::ambient::after(list, role, &Views { + image, + depth, + size: [of.Width as u32, of.Height], + slices: u32::from(of.DepthOrArraySize), + }) } /// What a draw or dispatch runs, for the device-removed report From a98966866c221ecd43b024922e67eacc6ca15dcc Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:09:23 -0600 Subject: [PATCH 14/31] Passes over the screen have pipeline workers and a wait of their own (VICTORY_SCREEN_WAIT_MS=0: not); after Belobug 18e57db8 The first run after a new translation (textures-d2: 2,500 pipelines being made, 594 draws a frame dropped in the world's first minute) had no lamps and no colour in the shade to its end; the second (textures-d3) had them. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/pipeline/host.rs | 11 +++ crates/victory-gpu/src/pipeline/make.rs | 119 +++++++++++++++++++----- 2 files changed, 106 insertions(+), 24 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index e3559c3..82c11ed 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -151,6 +151,17 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1 } impl GraphicsState { + /// Whether the draws are a pass over the screen: no vertex input, no + /// depth or stencil, a target. Such passes fill tables once; their shaders + /// are few. (After Belobug/VIctory-Belobug-AMD 18e57db8.) + pub(crate) fn screen_pass(&self) -> bool { + self.inputs.is_empty() + && (self.depth_format == DXGI_FORMAT_UNKNOWN + || !self.depth.DepthEnable.as_bool() && !self.depth.StencilEnable.as_bool()) + && self.targets.NumRenderTargets > 0 + && self.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE + } + /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). /// diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 3b6183e..4b591ed 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -13,7 +13,13 @@ //! whose pipeline is not ready is dropped, as an untranslated one is. //! //! The default budget is half a second per title frame. A pass the title -//! runs only once and whose pipeline takes longer is lost. +//! runs only once and whose pipeline takes longer is lost. Passes over the +//! screen (no vertex input, no depth) have workers and a longer budget of +//! their own ([`screen_budget`]): the title fills its lighting tables with +//! such draws once, at the world's first frame, and behind a world's worth of +//! pipelines they were dropped; that run had no lamps and no diffuse light to +//! its end (run textures-d2, the first after a new translation; Belobug +//! 18e57db8 found the same). use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; @@ -33,6 +39,8 @@ pub(crate) struct Pending { /// whether a draw or dispatch has requested it yet. key: String, used: AtomicBool, + /// A pass over the screen ([`GraphicsState::screen_pass`]). + screen: bool, } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -50,6 +58,7 @@ impl Pending { } key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); Pending { + screen: graphics.as_ref().is_some_and(|g| g.screen_pass()), shaders, graphics, queue_state: AtomicU8::new(NOT_QUEUED), @@ -113,6 +122,21 @@ fn wait_budget() -> Duration { }) } +/// As [`wait_budget`], for passes over the screen (`VICTORY_SCREEN_WAIT_MS`, +/// 10 s; 0: like the others). Below the title's 30 s watchdog. +fn screen_budget() -> Duration { + static BUDGET: OnceLock = OnceLock::new(); + *BUDGET.get_or_init(|| { + let millis = std::env::var("VICTORY_SCREEN_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(10_000); + Duration::from_millis(millis) + }) +} + +/// Whether passes over the screen go before the others. +fn screens_first() -> bool { + !screen_budget().is_zero() +} + /// Pipelines queued and not made yet. static WAITING: AtomicU64 = AtomicU64::new(0); @@ -167,16 +191,18 @@ fn shared_budget() -> bool { /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { - let budget = wait_budget(); + let screen = p.screen && screens_first(); + let budget = if screen { screen_budget() } else { wait_budget() }; if budget.is_zero() { return; } // The frame the budget belongs to, and what was waited of it (or is - // taken by a thread waiting now). - static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO)); + // taken by a thread waiting now); of the passes over the screen too. + static SPENT: [Mutex<(u64, Duration)>; 2] = [const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2]; + let spent_of = &SPENT[usize::from(screen)]; let shared = shared_budget(); let left = { - let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner()); if spent.0 != frame { *spent = (frame, Duration::ZERO); } @@ -201,8 +227,16 @@ fn wait(p: &Pending, frame: u64) { } drop(held); let waited = started.elapsed().min(left); + if screen && waited > Duration::from_millis(500) { + tracing::info!( + ms = waited.as_millis() as u64, + made = p.made.get().is_some(), + shaders = ?p.shaders, + "a pass over the screen was waited for (VICTORY_SCREEN_WAIT_MS=0: dropped past half a second a frame)" + ); + } { - let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner()); // A frame that began meanwhile has its own budget. if spent.0 == frame { if shared { @@ -225,6 +259,9 @@ const REQUESTED: u8 = 2; const MAKING: u8 = 3; struct Queue { + /// Requested passes over the screen: before all others, and the only ones + /// [`SCREEN_WORKERS`] take. + screen: VecDeque>, early: VecDeque>, requested: VecDeque>, } @@ -232,6 +269,7 @@ struct Queue { impl Queue { const fn new() -> Self { Self { + screen: VecDeque::new(), early: VecDeque::new(), requested: VecDeque::new(), } @@ -245,7 +283,9 @@ impl Queue { return None; } p.queue_state.store(priority, Ordering::Relaxed); - if priority == REQUESTED { + if priority == REQUESTED && p.screen && screens_first() { + self.screen.push_back(p.clone()); + } else if priority == REQUESTED { self.requested.push_back(p.clone()); } else { self.early.push_back(p.clone()); @@ -253,12 +293,16 @@ impl Queue { Some(prev == NOT_QUEUED) } - fn pop(&mut self) -> Option> { - let p = self.requested.pop_front().or_else(|| { - // An early entry can have been promoted and claimed already. - std::iter::from_fn(|| self.early.pop_front()) - .find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) - })?; + fn pop(&mut self, screens_only: bool) -> Option> { + let mut p = self.screen.pop_front(); + if p.is_none() && !screens_only { + p = self.requested.pop_front().or_else(|| { + // An early entry can have been promoted and claimed already. + std::iter::from_fn(|| self.early.pop_front()) + .find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) + }); + } + let p = p?; p.queue_state.store(MAKING, Ordering::Relaxed); Some(p) } @@ -284,14 +328,21 @@ fn start(p: &Arc, priority: u8) { if new { PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); } - AVAILABLE.notify_one(); + if p.screen { + AVAILABLE.notify_all(); + } else { + AVAILABLE.notify_one(); + } } } -fn next() -> Arc { +/// Workers that make passes over the screen alone, besides the others. +const SCREEN_WORKERS: usize = 2; + +fn next(screens_only: bool) -> Arc { let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); loop { - if let Some(p) = queue.pop() { + if let Some(p) = queue.pop(screens_only) { return p; } queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner()); @@ -320,14 +371,16 @@ fn workers() -> bool { std::thread::available_parallelism().map_or(2, |n| n.get()), ); tracing::info!(workers, "pipeline workers"); - for i in 0..workers { + let screens = if screens_first() { SCREEN_WORKERS } else { 0 }; + for i in 0..workers + screens { + let screens_only = i >= workers; let spawned = std::thread::Builder::new() .name(format!("victory-pipelines-{i}")) - .spawn(|| { + .spawn(move || { // Below the title's own threads (loading, recording), // and the streaming one, which is below normal itself // (`VICTORY_PIPELINE_LOWEST=0`: level with it, as before). - let lowest = std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0"); + let lowest = !screens_only && std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0"); // SAFETY: a plain call on our own thread. unsafe { use windows::Win32::System::Threading::*; @@ -335,7 +388,7 @@ fn workers() -> bool { let _ = SetThreadPriority(GetCurrentThread(), priority); } loop { - next().make(); + next(screens_only).make(); if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { @@ -425,10 +478,28 @@ mod tests { assert_eq!(queue.push(&promoted, REQUESTED), Some(false)); assert_eq!(queue.push(&promoted, REQUESTED), None); - assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested)); - assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted)); + assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &requested)); + assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &promoted)); assert_eq!(queue.push(&promoted, REQUESTED), None); - assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier)); - assert!(queue.pop().is_none()); + assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &earlier)); + assert!(queue.pop(false).is_none()); + } + + /// Passes over the screen go before all others, and workers of their own + /// take nothing else. + #[test] + fn passes_over_the_screen_go_first() { + let of = |screen| { + let mut p = Pending::new(Vec::new(), None); + p.screen = screen; + Arc::new(p) + }; + let (world, screen) = (of(false), of(true)); + let mut queue = Queue::new(); + assert_eq!(queue.push(&world, REQUESTED), Some(true)); + assert_eq!(queue.push(&screen, REQUESTED), Some(true)); + assert!(Arc::ptr_eq(&queue.pop(true).unwrap(), &screen)); + assert!(queue.pop(true).is_none()); + assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &world)); } } From 72f7f13242612ed0fab2937c0a55274de3439552 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:19:01 -0600 Subject: [PATCH 15/31] Ray tracing document: the stand-in, the sizes, what is known Co-Authored-By: Claude Opus 5.5 --- docs/fork-ray-tracing.md | 56 +++++++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index 6c05d8d..ec4a1ea 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -1,10 +1,10 @@ # Ray tracing in this fork: what the title does and what has been built -Status, 2026-11-25, 06:00: **with `VICTORY_BVH_BUILDER=1` the builder runs on -the RX 7900 XTX and rooms get their indirect light** (run light-6, the dorm: -bunk, locker, window frame, posters; 100-116 ms a frame against 84-95 without). -Some structures are still wrong; one run of four with it lost the device early, -in a list without a builder stage. Off by default. +Status, 2026-11-25, midday: **with `VICTORY_BVH_BUILDER=1` rooms get their +indirect light** (runs light-10, light-11, n19), for some 40 ms more of the +card's time a frame (the dorm: 75 of 90 ms busy against 34 of 64). Off by +default. **`VICTORY_AMBIENT=1`** puts an estimate of that light in its place +for next to nothing (below). ## What the title does @@ -92,6 +92,9 @@ after it was given them as an unordered access view. | variable | does | |---|---| | `VICTORY_BVH_BUILDER=1` | the builder's stages run | +| `VICTORY_BVH_FENCES=0` | no fences around the builder's buffer atomics (beloooo's 72e748ea has them too) | +| `VICTORY_BVH_SIZES_WAIT=0` | submissions that ask for structures' sizes are not waited for | +| `VICTORY_BVH_TRACE=1` | logs what sizes are asked, when they came, and the copies (diagnostics) | | `VICTORY_BVH_QUARANTINE=1` | nothing it stores comes back to title memory | | `VICTORY_MEMORY_CARD_MB` | the most of it on the card (4096) | | `VICTORY_MEMORY_DUMP=` | a file `go` there writes the arenas out (diagnostics) | @@ -102,10 +105,18 @@ dispatches, faults and what came. ## Known gaps -- About 4,000 pages a frame that are not there are still touched (the notes' - limit): some structures are wrong and rays go anywhere in them. Guess: sizes - that came back late or not (fixed after light-6, not seen working), so places - overlap. +- Dynamic structures overlap each other (8 of 65 good in run light-10). Cause, + run light-11's trace (`VICTORY_BVH_TRACE=1`): the title asks for a new + structure's compacted size, reads it one or two frames later without looking + whether it is there, takes memory of that size and has the structure copied + into it. Our submissions land up to two frames late; the title read what the + slot held before, another structure's size, and the copy wrote over the + neighbours. A submission that asks is waited for now + (`VICTORY_BVH_SIZES_WAIT=0`: not). +- Some 2,500 pages a frame that are not there are still touched (the notes' + limit): rays in structures that were written over. +- A capture of a frame with the builder on cannot be replayed: the card hangs + (cause unknown; do not try). - Five shadow-mask trace programs do not translate (a structure's address out of a descriptor picked from the heap by a computed index: the host would have to give a table of addresses by slot). The title did not create them in any @@ -116,6 +127,33 @@ dispatches, faults and what came. of two boxes entered at the same distance, and the result for a ray exactly through an edge. +## Without rays: the stand-in (`crates/victory-gpu/src/ambient.rs`) + +Without structures every ray misses. The title's program that resolves the +diffuse light of its screen probes (`CS_ScreenProbes_TemporalResolve_*`, list +184 of a frame) then leaves the sky's light outdoors, nothing indoors, and in +blocks of tiles what the probes' memory held. `VICTORY_AMBIENT=` raises +it to an estimate right after that program: the title keeps, for its own screen +traces, the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`, +1280x720, the frame before); its mean in 64x36 cells is gathered at 160x90 +points, each cell weighted by the share of the surroundings it covers, as a +directional value; each pixel takes it between the points by depth, with its +normal and a shade in creases. So level and tint follow the hour, the room and +its lamps. What the program left counts up to four times the estimate. + +Where it can be put, and the crease shade, are beloooo's (VIctory-Belobug-AMD +06031237, 4f45ab88, cd9f78ce); `VICTORY_AMBIENT=constant:` is that +fork's constant. + +| variable | does | +|---|---| +| `VICTORY_AMBIENT=` | the estimate, 1 all of it (unset: the title's own) | +| `VICTORY_AMBIENT=constant:` | the same light everywhere | +| `VICTORY_AMBIENT_SHADE=,` | the creases (1,0.6) | +| `VICTORY_AMBIENT_AIR=` | what the air scatters is bounded by a multiple of the light around (off) | + +It is off while the builder runs. + ## Where to look - `crates/victory-shader/src/bvh.rs`: the reference for the node test. From 6c17ce986f2282937795e9def68eba40f914edf1 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:36:58 -0600 Subject: [PATCH 16/31] Host heaps' slots are made under locks of their own; the heaps' records and the buffer views picked by index are made on several threads (VICTORY_VIEW_THREADS) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 33 +++- crates/victory-gpu/src/descriptor/host.rs | 174 ++++++++++++++-------- crates/victory-gpu/src/draw.rs | 80 ++++++---- crates/victory-gpu/src/land.rs | 20 ++- crates/victory-gpu/src/land/tests.rs | 6 +- 5 files changed, 206 insertions(+), 107 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 6585bfa..f5578c8 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -320,14 +320,22 @@ pub(crate) fn sync_heaps() { let mirrored_count = heap.desc.count.min(host.count()); // The records of some frames ago that no draw read through a table // since: a shader may pick them by index. - for index in host.copied_before(frame) { - if host.copied_tabled(index, frame) { - tabled += 1; - } else { - host.mirror(index, start + u64::from(index) * step, false); - mirrored += 1; + let before = host.copied_before(frame); + let of_tables = std::sync::atomic::AtomicU64::new(0); + crate::land::each_view(before.len().div_ceil(SYNC_AT_A_TIME), &|n| { + for &index in before.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { + if host.copied_tabled(index, frame) { + of_tables.fetch_add(1, Relaxed); + } else { + host.mirror(index, start + u64::from(index) * step, false); + } } - } + }); + let of_tables = of_tables.into_inner(); + tabled += of_tables; + mirrored += before.len() as u64 - of_tables; + // Those of the changed pages, made together at the end. + let mut make: Vec = Vec::new(); for (range_from, range_end) in written.take(start as usize, end as usize) { let mut page = range_from & !(crate::watch::PAGE - 1); while page < range_end { @@ -378,13 +386,18 @@ pub(crate) fn sync_heaps() { continue; } } - host.mirror(index, start + u64::from(index) * step, false); + make.push(index); mirrored += 1; } } page += crate::watch::PAGE; } } + crate::land::each_view(make.len().div_ceil(SYNC_AT_A_TIME), &|n| { + for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { + host.mirror(index, start + u64::from(index) * step, false); + } + }); if !wait.is_empty() { host.copied_wait(frame, std::mem::take(&mut wait)); } @@ -396,6 +409,10 @@ pub(crate) fn sync_heaps() { } } +/// Records [`sync_heaps`] gives a thread at a time. +#[cfg(windows)] +const SYNC_AT_A_TIME: usize = 256; + /// Since the last frame line, of [`sync_heaps`]: changed pages of placed /// shader-visible heaps looked at, slots on them, slots whose record was /// not the one last seen and was mirrored, the microseconds it took; then diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2e1c06a..43fe712 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -13,6 +13,45 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; +/// The record each slot of a heap was last made from, and a lock for every +/// few hundredth of the slots: whoever makes a slot holds its lock, and no +/// other. +/// +/// One lock for the heap was what everything of a frame waited for once the +/// lists were translated by threads of ours: half of what those did, two +/// thirds of the heaps' records and half of the pass over the buffer views +/// (profile thin-2). +struct Made { + keys: Vec, + locks: [Mutex<()>; Self::LOCKS], +} + +impl Made { + const LOCKS: usize = 512; + + fn new(count: usize) -> Self { + let mut keys = Vec::new(); + keys.resize_with(count, Default::default); + Made { keys, locks: [const { Mutex::new(()) }; Self::LOCKS] } + } + + /// The lock slot `index` is made under. Neighbours have different ones. + fn lock(&self, index: u32) -> std::sync::MutexGuard<'_, ()> { + self.locks[index as usize % Self::LOCKS].lock().unwrap_or_else(|e| e.into_inner()) + } + + fn get(&self, index: u32) -> Option { + Some(self.keys.get(index as usize)?.load(std::sync::atomic::Ordering::Acquire)) + } + + /// Under the slot's lock. + fn set(&self, index: u32, key: u64) { + if let Some(k) = self.keys.get(index as usize) { + k.store(key, std::sync::atomic::Ordering::Release); + } + } +} + pub(crate) struct HostHeap { pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, @@ -33,7 +72,7 @@ pub(crate) struct HostHeap { #[cfg(feature = "diagnostics")] written: Vec, /// The record (view index and generation) each slot was last made from. - made: Mutex>, + made: Made, /// The same for a slot whose descriptor is made and stays (else 0): what /// [`HostHeap::mirror`] asks first, without the lock. Changed under it. quick: Vec, @@ -1406,7 +1445,7 @@ impl HostHeap { written: (0..if sampler || !crate::book::on() { 0 } else { size }) .map(|_| std::sync::atomic::AtomicU32::new(0)) .collect(), - made: Mutex::new(vec![0; count as usize]), + made: Made::new(count as usize), quick: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), copied: Mutex::new(Vec::new()), waiting: Mutex::default(), @@ -1802,11 +1841,12 @@ impl HostHeap { // from a view the host could not make (`make` gave nothing, the // slot is null and keeps nothing). The host copy of such a // texture is held by no slot, may have been let go, and would be - // made anew here, with the card full. `made` first, then `kept`, - // as `mirror` takes them. - let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - made.get(index as usize).is_some_and(|&made| made != 0 && made == key) - && self.kept_in(index).is_some() + // made anew here, with the card full. + if key == 0 || self.made.get(index) != Some(key) { + return false; + } + let _made = self.made.lock(index); + self.made.get(index) == Some(key) && self.kept_in(index).is_some() } /// Levels on demand (`crate::tiles`): makes again the host slots of the @@ -1897,15 +1937,12 @@ impl HostHeap { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); starts.iter().flat_map(|&start| placed.slots_at(start)).collect() }; - let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); let mut remade = 0; for slot in slots { - let Some(&key) = made.get(slot as usize) else { + let _made = self.made.lock(slot); + let Some(key) = self.made.get(slot).filter(|&key| key != 0) else { continue; }; - if key == 0 { - continue; - } let Some(view) = view_at(key as u32, (key >> 32) as u32) else { continue; }; @@ -1935,8 +1972,8 @@ impl HostHeap { let wait = *WAIT.get_or_init(|| { std::env::var("VICTORY_TEXTURE_AWAY_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(AWAY_MS) }); - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - let Some(key) = made.get(index as usize).copied().filter(|&key| key != 0) else { + let _made = self.made.lock(index); + let Some(key) = self.made.get(index).filter(|&key| key != 0) else { return false; }; let now = crate::host::now_ms(); @@ -1954,7 +1991,7 @@ impl HostHeap { } } } - self.unmake(&mut made, index); + self.unmake(index); STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); true } @@ -1963,8 +2000,7 @@ impl HostHeap { /// at `handle` views, by an earlier view of it. pub(crate) fn texture_slot_shows_other(&self, index: u32, handle: u64) -> bool { let key = record_key(handle); - let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - let Some(&shown) = made.get(index as usize) else { + let Some(shown) = self.made.get(index) else { return false; }; if key == 0 || shown == 0 || shown == key { @@ -1992,33 +2028,31 @@ impl HostHeap { let (true, Some(view)) = (key != 0, view) else { return; }; - { - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - let Some(&shown) = made.get(index as usize) else { + let stale = { + let _made = self.made.lock(index); + let Some(shown) = self.made.get(index) else { return; }; if shown == key { return; } // (As `mirror`.) - for stale in self.note_buffer(index, Some(&view), true) { - if stale != index { - self.unmake(&mut made, stale); - } - } + let stale = self.note_buffer(index, Some(&view), true); let old = view_at(shown as u32, (shown >> 32) as u32); if shown == 0 || !old.is_some_and(|old| same_placed_texture(&old, &view)) { #[cfg(feature = "diagnostics")] note_before(index, shown, "neutral"); self.quick_is(index, 0); - made[index as usize] = 0; + self.made.set(index, 0); let kept = neutral_for(&view, self.at(index)); self.put(index); self.clear_twin(index); LATE[3].fetch_add(u64::from(kept.is_some()), Relaxed); self.keep(index, kept); } - } + stale + }; + self.unmake_stale(index, stale); self.flip(list, index, handle, Some(crate::frame::current())); } @@ -2065,18 +2099,18 @@ impl HostHeap { ready }; let mut flipped = 0; - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); for f in ready { - let Some(shown) = made.get_mut(f.index as usize) else { + let _made = self.made.lock(f.index); + let Some(shown) = self.made.get(f.index) else { continue; }; - if *shown == f.key { + if shown == f.key { continue; } // Written again since, or made null: that write is in the queue. // (A slot shown late is null until now.) let view = view_at(f.key as u32, (f.key >> 32) as u32); - let there = *shown != 0 || f.late.is_some(); + let there = shown != 0 || f.late.is_some(); let (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, there, view) else { FLIPPED[1].fetch_add(1, Relaxed); LATE[4].fetch_add(u64::from(f.late.is_some()), Relaxed); @@ -2095,9 +2129,9 @@ impl HostHeap { } if let Some(kept) = make(&view, self.at(f.index)) { #[cfg(feature = "diagnostics")] - note_before(f.index, *shown, if f.late.is_some() { "shown after its upload" } else { "flip" }); + note_before(f.index, shown, if f.late.is_some() { "shown after its upload" } else { "flip" }); self.put(f.index); - *shown = f.key; + self.made.set(f.index, f.key); self.keep(f.index, kept); if let Some(since) = f.late { let frames = crate::frame::current().saturating_sub(since); @@ -2131,12 +2165,13 @@ impl HostHeap { } /// Makes host slot `index` null again, as it is before its view is - /// made: a null view of the kind it held. - fn unmake(&self, made: &mut [u64], index: u32) { + /// made: a null view of the kind it held. Under its lock ([`Made`]). + fn unmake(&self, index: u32) { self.quick_is(index, 0); - let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { + let Some(key) = self.made.get(index) else { return; }; + self.made.set(index, 0); if key == 0 { return; } @@ -2149,6 +2184,21 @@ impl HostHeap { self.keep(index, None); } + /// The slots [`HostHeap::note_buffer`] found stale for slot `index`, with + /// what they were made from then, become null. None of their locks is + /// held here; one made from another record meanwhile is left as it is. + fn unmake_stale(&self, index: u32, stale: Vec<(u32, u64)>) { + for (slot, key) in stale { + if slot == index || key == 0 { + continue; + } + let _made = self.made.lock(slot); + if self.made.get(slot) == Some(key) { + self.unmake(slot); + } + } + } + /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a /// draw read it through the table and brought what it views up to /// date, so the slot leaves the queue of textures picked by index; the @@ -2258,9 +2308,11 @@ impl HostHeap { /// `seen`: the slot was not written now, a draw or a pass made its /// host slot from what it held. /// Returns the title slots whose placed texture view the write made - /// stale ([`Spans`]): out of the queue of textures already, their host - /// slots are the caller's to make null (it holds `made`). - fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec { + /// stale ([`Spans`]), each with the record its host slot is made from: + /// out of the queue of textures already, their host slots are the + /// caller's to make null when it has let go of its own slot's lock + /// ([`HostHeap::unmake_stale`]). + fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<(u32, u64)> { if self.sampler { return Vec::new(); } @@ -2310,7 +2362,9 @@ impl HostHeap { placed.rule = stale_rule(); let stale = placed.note(index, start, end, !seen); placed.shows(index, first, held); - stale + // (Under the lock of `placed`: a later write of one of + // them comes by here before it makes the slot.) + stale.into_iter().map(|slot| (slot, self.made.get(slot).unwrap_or(0))).collect() } None => { placed.forget(index); @@ -2321,7 +2375,7 @@ impl HostHeap { if !stale.is_empty() { STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); - for &slot in &stale { + for &(slot, _) in &stale { textures.remove(slot); } } @@ -2821,14 +2875,15 @@ impl HostHeap { { return Some(view); } - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let held = self.made.lock(index); + let shown = self.made.get(index).unwrap_or(0); let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); let Some(view) = view else { // Not a view of ours (never written, or of a resource the // title released): nothing to read. - if made[index as usize] != 0 { + if shown != 0 { self.quick_is(index, 0); - made[index as usize] = 0; + self.made.set(index, 0); self.make_null(index); let _ = self.note_buffer(index, None, false); } else if for_draw { @@ -2837,15 +2892,12 @@ impl HostHeap { } return None; }; - if made[index as usize] != key { + if shown != key { // Views of other textures in the memory this one describes // are stale: their host slots read nothing from here on, and // let go of the host copies they held. - for stale in self.note_buffer(index, Some(&view), for_draw) { - if stale != index { - self.unmake(&mut made, stale); - } - } + // (When this slot's lock is let go: a lock at a time.) + let stale = self.note_buffer(index, Some(&view), for_draw); // A view of a texture object that has no host copy yet waits // for it, as buffer views wait for a draw: the slot is made // when the texture is first used (`super::make_waiting`), or @@ -2864,18 +2916,20 @@ impl HostHeap { // time it got sharper. if later && keep_views() - && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32) + && view_at(shown as u32, (shown >> 32) as u32) .is_some_and(|old| same_placed_texture(&old, &view)) { KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + drop(held); + self.unmake_stale(index, stale); return Some(view); } #[cfg(feature = "diagnostics")] if !self.sampler && is_texture_view(&view) { - note_before(index, made[index as usize], if later { "null, waits" } else { "at once" }); + note_before(index, shown, if later { "null, waits" } else { "at once" }); } self.quick_is(index, 0); - made[index as usize] = if later { 0 } else { key }; + self.made.set(index, if later { 0 } else { key }); let kept = if later { None } else { @@ -2889,7 +2943,9 @@ impl HostHeap { } self.twin_made(index, kept.is_some() && twinned(&view)); self.keep(index, kept.flatten()); - self.quick_is(index, made[index as usize]); + self.quick_is(index, if later { 0 } else { key }); + drop(held); + self.unmake_stale(index, stale); } Some(view) } @@ -2905,11 +2961,7 @@ impl HostHeap { /// Whether slot `index` is backed by a made host descriptor (tests). #[cfg(test)] pub(crate) fn made(&self, index: u32) -> bool { - self.made - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(index as usize) - .is_some_and(|&key| key != 0) + self.made.get(index).is_some_and(|key| key != 0) } /// Whether host slot `index` shows `buffer`; `None` if it shows no @@ -2944,7 +2996,7 @@ impl HostHeap { /// a slot never made or left null. #[cfg(feature = "diagnostics")] pub(crate) fn describe_slot(&self, index: u32) -> Option { - let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + let key = self.made.get(index)?; if key == 0 { return Some("null".into()); } @@ -4920,7 +4972,7 @@ mod tests { assert_eq!(slots(50), []); assert_eq!(slots(51), [1]); // A wider texture written at the same address: slot 1 is stale. - assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]); + assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [(1, 0)]); assert_eq!(slots(u64::MAX), [2]); } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9889269..7001abc 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -761,48 +761,66 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho // Whether the device was there before the pass: a view that removes // it is named below. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + let alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); let mut unordered = Vec::new(); - for (n, &index) in slots.iter().enumerate() { - ranges.set(index, None); + /// The title's heap, for the threads that look. + struct Shared<'a>(&'a crate::descriptor::Heap); + // SAFETY: a heap is free-threaded (its methods are called by any thread of + // the title's), and it lives until all of them have looked. + unsafe impl Sync for Shared<'_> {} + impl Shared<'_> { + fn handle(&self, index: u32) -> Option { + self.0.handle(index) + } + } + let heap = Shared(heap); + // What a slot of the title's shows: its copy and range, and whether it is + // an unordered view. + let look = |index: u32| { // A draw's table's: the draw brings what it reads up to date. if host.copied_tabled(index, frame) { - continue; - } - let Some(handle) = heap.handle(index) else { - continue; - }; - let Some(view) = host.mirror(index, handle, true) else { - continue; - }; - // Every 64 views while the device lives (a cheap query). - if alive - && n % 64 == 63 - && let Some(why) = crate::descriptor::host::device_removed() - { - alive = false; - GONE.store(true, Ordering::Relaxed); - let last: Vec = slots[n - 63..=n] - .iter() - .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) - .map(|s| s.chars().take(200).collect()) - .collect(); - tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}"); - crate::host::log_removal_context(); + return None; } + let view = host.mirror(index, heap.handle(index)?, true)?; // The copy the slot shows (`buffer_copy`), not the one the // view's range alone would find. - let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else { - continue; - }; + let (shadow, address, len) = crate::descriptor::host::buffer_copy(&view)?; #[cfg(feature = "diagnostics")] if host.shows(index, &shadow.buffer) == Some(false) { HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); } - if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) { - unordered.push((shadow.clone(), address, address + len)); + let written = crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav); + Some(((shadow, address, address + len), written)) + }; + // Some slots at a time, on several threads. + const AT_A_TIME: usize = 256; + let parts: Vec<&[u32]> = slots.chunks(AT_A_TIME).collect(); + let found: Vec>> = parts.iter().map(|_| Default::default()).collect(); + crate::land::each_view(parts.len(), &|n| { + let looked: Vec<_> = parts[n].iter().map(|&index| (index, look(index))).collect(); + // (After each piece while the device lives: a cheap query.) + if alive + && let Some(why) = crate::descriptor::host::device_removed() + && !GONE.swap(true, Ordering::Relaxed) + { + let last: Vec = parts[n] + .iter() + .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) + .map(|s| s.chars().take(200).collect()) + .collect(); + tracing::error!(why, "the host device went while buffer views of the heap were made; perhaps one of: {last:#?}"); + crate::host::log_removal_context(); } - ranges.set(index, Some((shadow, address, address + len))); + let _ = found[n].set(looked); + }); + for (index, shows) in found.into_iter().filter_map(std::sync::OnceLock::into_inner).flatten() { + let range = shows.map(|(range, written)| { + if written { + unordered.push(range.clone()); + } + range + }); + ranges.set(index, range); } if crate::picked::on() { crate::picked::shown(unordered, all); diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 0bc5d5f..00b3ff1 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -227,7 +227,7 @@ impl Pool { self.state.lock().unwrap_or_else(|e| e.into_inner()) } - fn new(threads: usize) -> &'static Pool { + fn new(name: &'static str, threads: usize) -> &'static Pool { let pool: &'static Pool = Box::leak(Box::new(Pool { state: Mutex::new(State { work: None, next: 0, count: 0, running: 0, panicked: false }), more: Condvar::new(), @@ -237,8 +237,8 @@ impl Pool { })); for i in 1..threads { // (A helper that is not there is only missed.) - let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || { - crate::cores::keep_helper_on_fast_cores("victory-land"); + let _ = std::thread::Builder::new().name(format!("{name}-{i}")).spawn(move || { + crate::cores::keep_helper_on_fast_cores(name); pool.help() }); } @@ -321,7 +321,19 @@ fn take(state: &mut State) -> Option<(Work, usize)> { /// [`Pool::each`] on the threads kept for landing. pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) { static POOL: OnceLock<&'static Pool> = OnceLock::new(); - POOL.get_or_init(|| Pool::new(threads())).each(count, f); + POOL.get_or_init(|| Pool::new("victory-land", threads())).each(count, f); +} + +/// Calls `f` with every number below `count`, on this thread and on threads +/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 5 with this one; 1: +/// on this one alone). +pub(crate) fn each_view(count: usize, f: &(dyn Fn(usize) + Sync)) { + static POOL: OnceLock<&'static Pool> = OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(5usize); + Pool::new("victory-views", threads.clamp(1, 16)) + }) + .each(count, f); } /// A piece to land: the copy's number, the title address, its bytes. diff --git a/crates/victory-gpu/src/land/tests.rs b/crates/victory-gpu/src/land/tests.rs index f67d640..7e59e9d 100644 --- a/crates/victory-gpu/src/land/tests.rs +++ b/crates/victory-gpu/src/land/tests.rs @@ -48,7 +48,7 @@ impl Title { #[test] fn the_pool_calls_every_number_once() { for threads in [1usize, 2, 4, 7] { - let pool = Pool::new(threads); + let pool = Pool::new("victory-land", threads); std::thread::scope(|s| { for _ in 0..3 { s.spawn(|| { @@ -69,7 +69,7 @@ fn the_pool_calls_every_number_once() { /// A job that panics is told to the caller, and the pool goes on. #[test] fn a_panicking_job_reaches_the_caller() { - let pool = Pool::new(3); + let pool = Pool::new("victory-land", 3); for bad in 0..8usize { let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { pool.each(8, &|i| assert_ne!(i, bad, "(expected)")); @@ -448,7 +448,7 @@ fn what_landing_costs() { frame("as before, guards opened ahead", dense, 1, before); frame("as before, nothing guarded", dense, 0, before); for threads in [1usize, 2, 3, 4, 5, 6, 8] { - let pool = Pool::new(threads); + let pool = Pool::new("victory-land", threads); for beside in [false, true] { frame(&format!("{threads} threads, beside {beside}"), dense, 2, &|landing| { let cut: Vec<(usize, usize)> = landing.iter().map(|p| (p.0, BLOCK)).collect(); From 073d2d5bfdb9d945698ea230f72fdda831c17440 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:40:10 -0600 Subject: [PATCH 17/31] The panel shows what helps, and what it costs; nothing but a key asked for while it is off FPS, draws, the submitting thread, the card, waits, recording, MB a frame, memory; its own microseconds a frame on the submitting thread. VICTORY_PLACED_ORDER can be one of VICTORY_AB. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/card_steps.rs | 3 +- crates/victory-gpu/src/host/panel.rs | 94 ++++++++++------------- crates/victory-gpu/src/pipeline.rs | 6 -- 3 files changed, 42 insertions(+), 61 deletions(-) diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 9790941..6bd6a5f 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -93,8 +93,7 @@ pub(super) fn stage() -> u32 { /// place in a list. The whole submission was refused for it, and stood 40 to /// 60 ms until the flights had landed (run n19). fn placed_order() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_PLACED_ORDER").is_none_or(|v| v != "0")) + crate::toggled!("VICTORY_PLACED_ORDER") } /// Why [`plan`] refuses for [`place`]. diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs index 586d08f..a3d2f9b 100644 --- a/crates/victory-gpu/src/host/panel.rs +++ b/crates/victory-gpu/src/host/panel.rs @@ -1,7 +1,8 @@ //! Diagnostics: the run's numbers on the picture (`VICTORY_PANEL=1`; off by //! default; F3 shows and hides it while our window has the focus): white //! text on a black box in the upper left corner of what is shown, so that a -//! screenshot carries them. Made again twice a second from the counters of +//! screenshot carries them, with what it costs itself on the submitting +//! thread. Made again twice a second from the counters of //! the frame-rate line, memory and textures; a frame itself only copies the //! box out of a buffer in the card's memory. Copied onto the swap chain's //! buffer, behind the title's picture: saved frames and the frame recorder @@ -25,8 +26,8 @@ const EVERY: Duration = Duration::from_millis(500); const GLYPH: (u32, u32) = (5, 7); const CELL: (u32, u32) = (6, 9); /// Characters in a line, lines, and the box's rim in dots. -const COLUMNS: u32 = 43; -const LINES: u32 = 14; +const COLUMNS: u32 = 40; +const LINES: u32 = 9; const RIM: u32 = 3; /// The texts are put into one of these in turn: the card reads the others, @@ -171,29 +172,24 @@ fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> V #[derive(Clone, Copy, Default)] struct Counters([u64; COUNTERS]); -const COUNTERS: usize = 16; +const COUNTERS: usize = 11; impl Counters { fn now() -> Counters { - use super::{CARD_CLOCK_US, COPY_BACK, PREPARING, SUBMISSION_US}; + use super::{CARD_CLOCK_US, COPY_BACK, PREPARING}; use crate::copystat::{C, peek}; let get = |a: &std::sync::atomic::AtomicU64| a.load(Ordering::Relaxed); Counters([ - get(&SUBMISSION_US[0]), - get(&PREPARING[0]), - get(&PREPARING[1]), - get(&PREPARING[2]), - get(&PREPARING[3]), - get(©_BACK[0]), - get(©_BACK[1]), + super::worked(), get(&CARD_CLOCK_US[0]), get(&CARD_CLOCK_US[1]), get(&CARD_CLOCK_US[2]), + get(&PREPARING[3]), + get(©_BACK[0]), + get(©_BACK[1]), get(&crate::shadow::CARD_STATS[0]), crate::draw::dropped_now(), peek(C::RecordNs), - peek(C::RecordCalls), - peek(C::Submissions), crate::draw::drawn(), ]) } @@ -210,43 +206,22 @@ impl Counters { } /// The text. `c`: [`Counters`] per frame, `ms` a frame's time, `worst` the -/// longest frame's. -fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, host: &Host) -> Vec { - use crate::draw::{ - HEAP_TEXTURE_BYTES, HEAP_TEXTURES, HEAP_TEXTURES_AWAY, HEAP_TEXTURES_FULL, HEAP_TEXTURES_WAITING, - }; +/// longest frame's, `cost` what this takes of a frame, in microseconds. +fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec { let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64; - let get = |a: &std::sync::atomic::AtomicU64| a.load(Ordering::Relaxed); let (working, private) = crate::copystat::process_memory(); let [budget, used, _, shared] = host.video_memory().unwrap_or_default(); - let (hits, misses) = crate::shader_cache::counts(); - let failed = get(&crate::pipeline::FAILED); - let idle = (c[7] / 1e3).min(ms); + let idle = (c[1] / 1e3).min(ms); vec![ format!("FPS {:.1} FRAME {ms:.1} MS LONGEST {worst:.0}", 1e3 / ms.max(0.001)), - format!("DRAWS {:.0} DROPPED {:.1} SUBMITS {:.1}", c[15], c[11], c[14]), - format!("CPU PREP {:.1} MS COPY {:.1} TEXTURES {:.1}", c[0] / 1e3, c[1] / 1e3, c[3] / 1e3), - format!("RECORDING {:.0} MS IN {:.0} CALLS", c[12] / 1e6, c[13]), - format!("GPU BUSY {:.1} MS IDLE {idle:.1} BEHIND US {:.1}", ms - idle, c[8] / 1e3), - format!("WAIT FOR GPU {:.1} MS COPY BACK {:.1} MS", c[9] / 1e3, c[5] / 1e3), - format!("MB UP {:.1} ON CARD {:.1} TEX {:.1} BACK {:.1}", c[2] / 1e6, c[10] / 1e6, c[4] / 1e6, c[6] / 1e6), - format!("RAM PRIVATE {:.1} GB IN MEMORY {:.1} GB", gb(private), gb(working)), - format!("VRAM {:.1}/{:.1} GB SHARED {:.1} GB", gb(used), gb(budget), gb(shared)), - format!( - "TEXTURES {} {:.1} GB WAITING {}", - get(&HEAP_TEXTURES), - gb(get(&HEAP_TEXTURE_BYTES)), - get(&HEAP_TEXTURES_WAITING) - ), - format!( - "UNMAPPED {} NO ROOM {} VIEWS {}", - get(&HEAP_TEXTURES_AWAY), - get(&HEAP_TEXTURES_FULL), - get(&crate::descriptor::host::REFUSED_VIEWS) - ), - format!("SHADERS CACHED {hits} NEW {misses} FAILED {failed}"), - format!("PIPELINES QUEUED {}", crate::pipeline::making()), - format!("FRAME NO {}", crate::queue::presented()), + format!("DRAWS {:.0} DROPPED {:.0}", c[10], c[8]), + format!("SUBMIT BUSY {:.1} WAITS FOR GPU {:.1}", c[0] / 1e3, c[3] / 1e3), + format!("GPU BUSY {:.1} IDLE BEHIND US {:.1}", ms - idle, c[2] / 1e3), + format!("RECORDING {:.0} MS COPY BACK {:.1}", c[9] / 1e6, c[5] / 1e3), + format!("MB UP {:.0} TEXTURES {:.0} BACK {:.0}", c[7] / 1e6, c[4] / 1e6, c[6] / 1e6), + format!("RAM {:.1} GB IN MEMORY {:.1}", gb(private), gb(working)), + format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)), + format!("THIS PANEL {:.0} US A FRAME", cost), ] } @@ -312,6 +287,8 @@ pub(super) struct Panel { frames: u32, last: Instant, worst: f64, + /// What this took since the last text. + cost: Duration, before: Counters, lines: Vec, changed: bool, @@ -327,6 +304,7 @@ impl Panel { frames: 0, last: now, worst: 0.0, + cost: Duration::ZERO, before: Counters::default(), lines: Vec::new(), changed: false, @@ -336,12 +314,21 @@ impl Panel { } /// A frame was presented; `line`: the counters go back to 0 right behind - /// this call. + /// this call. (Not shown it asks for the key's state and no more.) pub(super) fn frame(&mut self, line: bool) { if pressed() { shown().fetch_xor(true, Ordering::Relaxed); } + if !shown().load(Ordering::Relaxed) { + self.frames = 0; + return; + } let now = Instant::now(); + if self.frames == 0 && now - self.last > 2 * EVERY { + // (Shown from here on.) + (self.since, self.last, self.worst, self.before) = (now, now, 0.0, Counters::now()); + self.frames = 0; + } self.frames += 1; self.worst = self.worst.max((now - self.last).as_secs_f64() * 1e3); self.last = now; @@ -349,17 +336,16 @@ impl Panel { if elapsed < EVERY && !(line && elapsed * 2 >= EVERY) { return; } - let (frames, worst) = (f64::from(self.frames), self.worst); - (self.since, self.frames, self.worst) = (now, 0, 0.0); - if !shown().load(Ordering::Relaxed) { - return; - } let Some(host) = super::host() else { return }; + let frames = f64::from(self.frames); let counters = Counters::now(); let c = counters.since(self.before, frames); self.before = counters; - self.lines = text(&c, elapsed.as_secs_f64() * 1e3 / frames, worst, host); + let cost = self.cost.as_secs_f64() * 1e6 / frames; + self.lines = text(&c, elapsed.as_secs_f64() * 1e3 / frames, self.worst, cost, host); self.changed = true; + (self.since, self.frames, self.worst) = (now, 0, 0.0); + self.cost = now.elapsed(); } /// Records the copy of the box onto `back`, a buffer of the swap chain of @@ -375,6 +361,7 @@ impl Panel { if !shown().load(Ordering::Relaxed) || self.lines.is_empty() || self.failed { return; } + let began = Instant::now(); // Not the title's: the frame recorder leaves it out. let _ours = crate::replay::record::unrecorded(); let scale = scale(height); @@ -432,6 +419,7 @@ impl Panel { }; list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&part)); } + self.cost += began.elapsed(); } } diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 0945b4c..7a00633 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -78,9 +78,6 @@ static SHADERS: Mutex>>> = Mutex::new(None) /// kept and the bytes of their host code. None of them is ever let go. static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; -/// Shaders that did not translate. -pub(crate) static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - /// What the shader table and the pipeline library keep in memory: /// containers and their bytes, translations and their bytes, the bytes of /// the library's file (kept whole while the library lives) and what its @@ -161,9 +158,6 @@ impl Shader { KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed); } - if done.is_err() { - FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } match &done { Ok(t) => tracing::info!( stage = self.stage, From d79ec0ebd6abb350f84caa4253fec25fb16ccf0c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:40:10 -0600 Subject: [PATCH 18/31] Two measurements for placing memory: bytes over the bus by host copy, and what the title asks its memory to be Diagnostics: per copy what goes up and what is fetched (every five seconds, the eight that move most), and the protections title memory is asked for with (write-combined and GPU bits). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 9 ++++ crates/victory-gpu/src/host/traffic.rs | 61 ++++++++++++++++++++++++++ crates/victory-hle/src/modules/xmem.rs | 24 ++++++++++ 3 files changed, 94 insertions(+) create mode 100644 crates/victory-gpu/src/host/traffic.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 126a292..5adda57 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3564,6 +3564,8 @@ pub(crate) use send::{goes_as_words, words_under}; #[cfg(feature = "diagnostics")] pub(crate) mod spans; mod torn; +#[cfg(feature = "diagnostics")] +mod traffic; pub(crate) mod upcheck; #[cfg(feature = "diagnostics")] mod stamps; @@ -4184,6 +4186,8 @@ impl Host { crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); } crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + traffic::moved(traffic::UP, shadow.span(), ranges.iter().copied()); if own.is_none() && before.is_some() && !ranges.is_empty() { sent.push(transition( &shadow.buffer, @@ -4527,6 +4531,10 @@ impl Host { if let Some(check) = &check { total = check.total; } + #[cfg(feature = "diagnostics")] + for (shadow, lo, hi, _) in &pieces { + traffic::moved(traffic::FETCHED, shadow.span(), std::iter::once((*lo, *hi))); + } // The sends these flights ran behind, all a fetch on the copy queue // is known to have run behind. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0); @@ -8551,6 +8559,7 @@ impl Meter { put[2] / 1e6, put[3] ); + traffic::line(self.copy_stats_frames as f64); crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); for (why, n) in drops.iter().take(40) { tracing::info!( diff --git a/crates/victory-gpu/src/host/traffic.rs b/crates/victory-gpu/src/host/traffic.rs new file mode 100644 index 0000000..92a003c --- /dev/null +++ b/crates/victory-gpu/src/host/traffic.rs @@ -0,0 +1,61 @@ +//! Diagnostics: which host copies' bytes cross the bus, and which way: per +//! copy (title address, bytes) what was sent up and what shaders wrote that +//! was fetched, a frame; and how many different 64 KiB pieces of it. Every +//! five seconds, the eight that move most. For placing resources: a copy whose +//! pieces are fetched every frame and never sent up is written by shaders +//! alone, and nobody but shaders may read it. + +use std::collections::{HashMap, HashSet}; +use std::sync::Mutex; + +/// Of a copy, each way (up, fetched): bytes, and the pieces (64 KiB). +#[derive(Default)] +struct Moved { + bytes: [u64; 2], + pieces: [HashSet; 2], +} + +pub(super) const UP: usize = 0; +pub(super) const FETCHED: usize = 1; + +static MOVED: Mutex>> = Mutex::new(None); + +/// Offsets `ranges` of the copy of `span` (title address, bytes) went `way`. +pub(super) fn moved(way: usize, span: (u64, u64), ranges: impl Iterator) { + let mut all = MOVED.lock().unwrap_or_else(|e| e.into_inner()); + let m = all.get_or_insert_with(Default::default).entry(span).or_default(); + for (from, to) in ranges.filter(|r| r.0 < r.1) { + m.bytes[way] += (to - from) as u64; + m.pieces[way].extend((from >> 16) as u32..=((to - 1) >> 16) as u32); + } +} + +/// For the log, over `frames` frames. +pub(super) fn line(frames: f64) { + let all = MOVED.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let mut all: Vec<_> = all.into_iter().collect(); + all.sort_by_key(|(_, m)| std::cmp::Reverse(m.bytes[0] + m.bytes[1])); + let mb = |b: u64| b as f64 / 1e6 / frames.max(1.0); + let sum = |way: usize| all.iter().map(|(_, m)| m.bytes[way]).sum::(); + // Copies that only move one way. + let only = |way: usize| all.iter().filter(|(_, m)| m.bytes[1 - way] == 0).map(|(_, m)| m.bytes[way]).sum::(); + tracing::info!( + "bytes of host copies over the bus per frame: {:.1} MB up ({:.1} of copies nothing was fetched from), {:.1} MB fetched \ + ({:.1} of copies nothing was sent up to), {} copies; the most:", + mb(sum(UP)), + mb(only(UP)), + mb(sum(FETCHED)), + mb(only(FETCHED)), + all.len() + ); + for ((start, len), m) in all.into_iter().take(8) { + let both = m.pieces[0].intersection(&m.pieces[1]).count(); + tracing::info!( + " {start:#x}+{len:#x}: {:.2} MB up in {} different pieces, {:.2} MB fetched in {}, {both} of them both ways", + mb(m.bytes[0]), + m.pieces[0].len(), + mb(m.bytes[1]), + m.pieces[1].len() + ); + } +} diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index ad0cdb1..80b3437 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -101,6 +101,7 @@ pub extern "system" fn XMemVirtualAlloc( 0 }, }; + let asked = protect; let mut protect = match protect & HOST_PROTECTION { 0 => PAGE_NOACCESS, p => p, @@ -179,9 +180,32 @@ pub extern "system" fn XMemVirtualAlloc( if !at.is_null() && !placeholder { victory_gpu::title_memory_allocated(at as usize, size); } + note_protection(asked, kind, flags, at as usize, size); at } +/// What the title asks its memory to be (the console's protection, with the +/// bits that say how each processor reaches it: 0x200 uncached, 0x400 +/// write-combined, 0x800 and on the GPU's): said for the 1st, 2nd, 4th.. time of +/// each, with how much so far. (For placing it: memory the CPU reaches +/// uncached or write-combined is memory it does not read.) +fn note_protection(protect: u32, kind: u32, flags: u64, at: usize, size: usize) { + type Seen = std::collections::HashMap<(u32, u32, u64), (u64, usize)>; + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(None); + let (n, bytes) = { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let e = seen.get_or_insert_with(Default::default).entry((protect, kind, flags)).or_default(); + *e = (e.0 + 1, e.1 + size); + *e + }; + if n.is_power_of_two() { + tracing::info!( + "title memory asked for as protection {protect:#x}, kind {kind:#x}, flags {flags:#x}: {n} times, {} MB, last {at:#x}+{size:#x}", + bytes >> 20 + ); + } +} + /// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the /// same), then the XMem flags and tag. #[repr(C)] From f19e55b8b69cfb3f5a5e68f54317b97f82c9e2fa Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:41:23 -0600 Subject: [PATCH 19/31] The title's writes into guarded blocks go in beside the guard: its memcpy, memmove and memset (VICTORY_COPY_BESIDE=1) and single stores that fault (VICTORY_STORE_BESIDE=1); both off Most of what faults is the runtime's memcpy (a third by time) and single stores into objects that lie in memory some copy covers: flags, reference counts, links of free lists. The bytes are put in through our own view of the page, the block told as written at every view by a bit that the next asking takes: no protection changes, for the write or for the next taking. Copies: the title's imports are ours and look at the blocks' bits. Stores: the instruction that faulted is decoded and done in the handler. Too many to a block, or code that fills blocks: opened as before. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/copystat.rs | 6 + crates/victory-gpu/src/faultbook.rs | 7 +- crates/victory-gpu/src/inplace.rs | 28 + crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/titlewrite.rs | 290 +++++++++ crates/victory-gpu/src/titlewrite/decode.rs | 632 ++++++++++++++++++++ crates/victory-gpu/src/watch.rs | 272 ++++++++- crates/victory-hle/src/host.rs | 8 + 8 files changed, 1229 insertions(+), 16 deletions(-) create mode 100644 crates/victory-gpu/src/titlewrite.rs create mode 100644 crates/victory-gpu/src/titlewrite/decode.rs diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 484c90a..6fa7971 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1203,6 +1203,12 @@ pub(crate) fn log(frames: f64) { "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" ); + let [copies, blocks, opened, stores, unknown, full] = + [0, 1, 2, 3, 4, 5].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); + tracing::info!( + "the title's writes beside the guards, since the start: {copies} copies (VICTORY_COPY_BESIDE=1), {blocks} blocks, {opened} opened; \ + {stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many" + ); // Where the wall clock of a frame goes: the phases of a frame, the // processor time of the whole process, and what each submitting and // recording thread did. diff --git a/crates/victory-gpu/src/faultbook.rs b/crates/victory-gpu/src/faultbook.rs index 9fca8fa..1b0db43 100644 --- a/crates/victory-gpu/src/faultbook.rs +++ b/crates/victory-gpu/src/faultbook.rs @@ -32,8 +32,11 @@ pub(crate) enum What { Alias = 6, /// A fault on block `a` that someone else had opened; b: nanoseconds. Open = 7, - /// Blocks `[a, b)` were opened ahead of the title's writes. - Ahead = 8, + /// The instruction at `a` made the fault before (block `b`). + Site = 9, + /// A store (the instruction at `a`) was done beside the guard of block + /// `b`. + Stored = 10, } #[repr(C)] diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 8679e68..28f570e 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -565,6 +565,34 @@ pub(crate) fn beside(at: usize, len: usize) -> Option { (base != 0).then(|| base + offset as usize) } +/// Our own address of the 64 KiB page the title sees at `page` ([`beside`]), +/// and every address the title sees it at (0: no more); `None` if the page is +/// in no view of a section, or in very many. While the caller holds +/// `crate::watch::title_memory_reading`. +pub(crate) fn beside_page(page: usize) -> Option<(usize, [usize; 8])> { + for asked in [false, true] { + { + let v = views(); + let (&base, &(bytes, section, offset)) = v.views.range(..=page).next_back()?; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return None; + } + let offset = offset + within as u64; + if let Some(whole) = v.whole.iter().find(|w| w.0 == section) { + let mut shown = [0; 8]; + let all = v.pages.get(&(section, offset))?; + shown.get_mut(..all.len())?.copy_from_slice(all); + return (whole.1 != 0).then(|| (whole.1 + offset as usize, shown)); + } + } + if asked || beside(page, K64).is_none() { + return None; + } + } + None +} + /// Whether `[at, at + len)` is private memory, all committed and /// read-write: what [`From::Part`] takes. One question to Windows (it /// walks the page tables to the end of the pages that share the first diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 1147880..f725253 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -78,6 +78,8 @@ mod tdr; mod texture; pub mod timeline; #[cfg(windows)] +pub mod titlewrite; +#[cfg(windows)] mod upload; #[cfg(windows)] mod watch; diff --git a/crates/victory-gpu/src/titlewrite.rs b/crates/victory-gpu/src/titlewrite.rs new file mode 100644 index 0000000..08aee3a --- /dev/null +++ b/crates/victory-gpu/src/titlewrite.rs @@ -0,0 +1,290 @@ +//! The title's writes into guarded view memory that do not go through a +//! fault that opens the block (`crate::watch`): its bytes are put in through +//! our own view of the same pages (`crate::inplace`), which no guard covers, +//! and the block is told as written (`crate::watch::put_beside`). The block +//! stays read-only, so neither this write nor the block's next taking changes +//! a protection. +//! +//! A change of protection is some 5 us in the game's process, one at a time +//! whoever asks; a frame had 590 write faults, and made as many blocks +//! read-only again (run faults-1). What faults is, by the time spent in it, +//! for a third the title's `memcpy`, and for most of the rest single stores +//! into objects that lie in memory some buffer's copy covers: a flag, a +//! reference count, the link of a free list. +//! +//! - [`import`]: the title's `memcpy`, `memmove` and `memset` are ours +//! (`VICTORY_COPY_BESIDE=1`; off unless asked for). They look at the bits +//! of the blocks they write and go to the runtime's own, but for the parts +//! that lie in guarded blocks. +//! - [`store`]: a store that faults is done here, and the thread goes on +//! behind it (`VICTORY_STORE_BESIDE=1`; off unless asked for). Nothing of +//! the title's code is known ahead: the instruction is read where it +//! faulted, and one that is not understood opens the block as before. So +//! does a block's fifth store since it was taken, and one at a place in the +//! code most of whose blocks come to that ([`SITES`]): code that fills a +//! block would fault at every store. + +mod decode; + +use crate::watch::Beside; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; + +/// Diagnostics, since the start: copies of the title's that put bytes beside +/// the guards, blocks they did so in, blocks they opened instead; stores done +/// beside the guards, faulting stores not understood, and blocks opened +/// because too many came. +pub(crate) static DONE: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +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") +} + +fn stores_on() -> bool { + #[cfg(test)] + if ON_IN_TEST.get() { + return true; + } + asked_for!("VICTORY_STORE_BESIDE") +} + +#[cfg(test)] +thread_local! { + /// Both, for this thread's writes. + pub(crate) static ON_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The runtime's own `memcpy`, `memmove` and `memset`. +static REAL: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3]; + +type Copy = unsafe extern "system-unwind" fn(*mut u8, *const u8, usize) -> *mut u8; +type Set = unsafe extern "system-unwind" fn(*mut u8, i32, usize) -> *mut u8; + +/// What the title's import of `name`, which the host has at `address`, is +/// bound to. +pub fn import(name: &str, address: usize) -> usize { + let (which, ours) = match name { + "memcpy" => (0, copy as *const () as usize), + "memmove" => (1, shift as *const () as usize), + "memset" => (2, set as *const () as usize), + _ => return address, + }; + #[cfg(feature = "diagnostics")] + let on = crate::ab::bit("VICTORY_COPY_BESIDE").is_some() || copies_on(); + #[cfg(not(feature = "diagnostics"))] + let on = copies_on(); + if !on { + return address; + } + REAL[which].store(address, Relaxed); + ours +} + +#[cfg(test)] +pub(crate) fn copy_for_test(real: usize) -> usize { + REAL[0].store(real, Relaxed); + copy as *const () as usize +} + +/// The most a block takes of copies beside its guard before it is opened; a +/// store counts as [`A_STORE`]. +pub(crate) const MOST: u32 = 32; +const A_STORE: u32 = 8; + +unsafe extern "system-unwind" fn copy(to: *mut u8, from: *const u8, n: usize) -> *mut u8 { + // SAFETY: the title's copy, as it asked for it, by the function it asked. + unsafe { copied(to, from, n, REAL[0].load(Relaxed)) } +} + +unsafe extern "system-unwind" fn shift(to: *mut u8, from: *const u8, n: usize) -> *mut u8 { + // SAFETY: as above. + unsafe { copied(to, from, n, REAL[1].load(Relaxed)) } +} + +/// # Safety +/// `real` copies as `memcpy` (or `memmove`) does, `to`, `from` and `n` are +/// the title's. +#[inline] +unsafe fn copied(to: *mut u8, from: *const u8, n: usize, real: usize) -> *mut u8 { + // SAFETY: the host's function, noted by `import` before the title ran. + let real: Copy = unsafe { std::mem::transmute(real) }; + if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() || overlap(to as usize, from as usize, n) { + // SAFETY: by the caller. + return unsafe { real(to, from, n) }; + } + in_pieces(to as usize, n, |at, offset, len| { + // SAFETY: a part of what the title asked for; or the same bytes at + // our view of the pages. + unsafe { real(at as *mut u8, from.add(offset), len) }; + }); + to +} + +unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u8 { + // SAFETY: as in `copied`. + let real: Set = unsafe { std::mem::transmute(REAL[2].load(Relaxed)) }; + if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() { + // SAFETY: the title's, as it asked for it. + return unsafe { real(to, byte, n) }; + } + in_pieces(to as usize, n, |at, _, len| { + // SAFETY: as in `copied`. + unsafe { real(at as *mut u8, byte, len) }; + }); + to +} + +/// Whether the two ranges meet, if only in a block (of which only one might +/// be written at another address). +fn overlap(to: usize, from: usize, n: usize) -> bool { + const BLOCK: usize = crate::watch::PAGE; + let (first, last) = (to / BLOCK * BLOCK, to.saturating_add(n).next_multiple_of(BLOCK)); + from < last && first < from.saturating_add(n) +} + +/// Does `[to, to + n)` block by block: `put(at, offset, len)` with the +/// address to write at, the title's or ours. +fn in_pieces(to: usize, n: usize, put: impl Fn(usize, usize, usize)) { + const BLOCK: usize = crate::watch::PAGE; + add(0); + let mut offset = 0; + while offset < n { + let at = to + offset; + let len = (BLOCK - at % BLOCK).min(n - offset); + if crate::watch::guards_any(at, len) { + match crate::watch::put_beside(at / BLOCK, 1, |delta| put(at.wrapping_add(delta), offset, len)) { + Beside::Done => { + add(1); + offset += len; + continue; + } + // Opened with no fault: the next copies here are plain ones. + _ => crate::watch::opened_for_writing(at), + } + add(2); + } + put(at, offset, len); + offset += len; + } +} + +/// Places of the title's code whose stores faulted, by a hash of the address: +/// the stores done beside the guards (the low half) and the blocks that had +/// too many of them (the high half). +static SITES: [AtomicU64; 1 << 10] = [const { AtomicU64::new(0) }; 1 << 10]; + +fn site(rip: usize) -> &'static AtomicU64 { + &SITES[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 54 & 1023] +} + +/// Whether a site's stores come one to a block, as far as is known. +fn sparse(counts: u64) -> bool { + let (done, full) = (counts & 0xffff_ffff, counts >> 32); + full < 4 || full * 12 < done +} + +/// Does the store that faulted at `at`, a byte of a guarded block, beside the +/// guards; `false` if it is to open the block (and nothing was done). +pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, at: usize) -> bool { + if !stores_on() { + return false; + } + let rip = context.Rip as usize; + let site = site(rip); + let counts = site.load(Relaxed); + if !sparse(counts) { + // Looked at anew some time. + if site.fetch_add(1 << 32, Relaxed) >> 32 > 4096 { + site.store(0, Relaxed); + } + return false; + } + let mut code = [0u8; 15]; + // (To the end of the page if the next is not there.) + let left = 4096 - rip % 4096; + let there = crate::host::read_into(rip as *const u8, &mut code) || { + let n = left.min(15); + n < 15 && crate::host::read_into(rip as *const u8, &mut code[..n]) + }; + let Some(store) = there.then(|| decode::store(&code, context)).flatten() else { + add(4); + return false; + }; + const BLOCK: usize = crate::watch::PAGE; + let end = store.at.wrapping_add(store.size); + if !(store.at..end).contains(&at) || store.at / BLOCK != (end - 1) / BLOCK { + add(4); + return false; + } + let mut done = false; + let put = crate::watch::put_beside(store.at / BLOCK, A_STORE, |delta| { + // SAFETY: the bytes the title is storing to, at our view of them. + done = unsafe { store.run(context, store.at.wrapping_add(delta)) }; + }); + if put != Beside::Done { + if put == Beside::Full { + site.fetch_add(1 << 32, Relaxed); + add(5); + } + return false; + } + if !done { + // (A locked one that is not aligned: told as written for nothing.) + add(4); + return false; + } + context.Rip += store.len as u64; + site.fetch_add(1, Relaxed); + add(3); + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Stored, rip, at / BLOCK, 0); + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sites_that_fill_blocks_are_told_from_others() { + assert!(sparse(0) && sparse(1000) && sparse(3 << 32)); + assert!(!sparse(4 << 32 | 16) && sparse(4 << 32 | 60)); + } + + #[test] + fn copies_that_meet_are_left_to_the_runtime() { + const B: usize = crate::watch::PAGE; + assert!(overlap(10 * B + 5, 10 * B + 900, 8), "in one block"); + assert!(!overlap(10 * B + 5, 12 * B, 8) && !overlap(10 * B, 9 * B, B)); + assert!(overlap(10 * B, 9 * B, B + 1)); + } +} diff --git a/crates/victory-gpu/src/titlewrite/decode.rs b/crates/victory-gpu/src/titlewrite/decode.rs new file mode 100644 index 0000000..4c1bd67 --- /dev/null +++ b/crates/victory-gpu/src/titlewrite/decode.rs @@ -0,0 +1,632 @@ +//! The stores of x86-64 code that [`super::store`] does in the title's place: +//! moves from a register or a constant, arithmetic of those with memory +//! (locked or not), exchanges, and the 4, 8 and 16 byte stores of the vector +//! registers. Everything else is `None`. + +use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering::SeqCst}; +use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Alu { + Add, + Or, + And, + Sub, + Xor, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Op { + /// These bytes (the low `size` of them). + Put([u8; 16]), + /// With a value; `keeps` carry (`inc`, `dec`). + Alu { alu: Alu, with: u64, keeps: bool }, + /// With a register, which gets what was there. + Xchg(Register), + Xadd(Register), + Cmpxchg(Register), +} + +/// A general register, or (`high`) the second byte of one of the first four. +#[derive(Clone, Copy, PartialEq, Debug)] +struct Register { + number: usize, + high: bool, +} + +pub(super) struct Store { + /// Where it stores, and how many bytes. + pub(super) at: usize, + pub(super) size: usize, + /// The instruction's length. + pub(super) len: usize, + op: Op, + locked: bool, +} + +fn general(c: &CONTEXT, number: usize) -> u64 { + match number { + 0 => c.Rax, + 1 => c.Rcx, + 2 => c.Rdx, + 3 => c.Rbx, + 4 => c.Rsp, + 5 => c.Rbp, + 6 => c.Rsi, + 7 => c.Rdi, + 8 => c.R8, + 9 => c.R9, + 10 => c.R10, + 11 => c.R11, + 12 => c.R12, + 13 => c.R13, + 14 => c.R14, + _ => c.R15, + } +} + +fn general_mut(c: &mut CONTEXT, number: usize) -> &mut u64 { + match number { + 0 => &mut c.Rax, + 1 => &mut c.Rcx, + 2 => &mut c.Rdx, + 3 => &mut c.Rbx, + 4 => &mut c.Rsp, + 5 => &mut c.Rbp, + 6 => &mut c.Rsi, + 7 => &mut c.Rdi, + 8 => &mut c.R8, + 9 => &mut c.R9, + 10 => &mut c.R10, + 11 => &mut c.R11, + 12 => &mut c.R12, + 13 => &mut c.R13, + 14 => &mut c.R14, + _ => &mut c.R15, + } +} + +impl Register { + /// Operand `number` of `size` bytes, with or without a REX prefix. + fn of(number: usize, size: usize, rex: bool) -> Register { + if size == 1 && !rex && (4..8).contains(&number) { + Register { number: number - 4, high: true } + } else { + Register { number, high: false } + } + } + + fn get(self, c: &CONTEXT) -> u64 { + general(c, self.number) >> if self.high { 8 } else { 0 } + } + + /// As an instruction writes it: 32 bits clear the rest, fewer leave it. + fn put(self, c: &mut CONTEXT, value: u64, size: usize) { + let register = general_mut(c, self.number); + let shift = if self.high { 8 } else { 0 }; + *register = match size { + 8 => value, + 4 => value & 0xffff_ffff, + _ => *register & !(mask(size) << shift) | (value & mask(size)) << shift, + }; + } +} + +fn mask(size: usize) -> u64 { + if size >= 8 { u64::MAX } else { (1 << (size * 8)) - 1 } +} + +/// The store at the start of `code`, which the registers are those of. +pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { + let mut at = 0; + let mut next = || { + let byte = code.get(at).copied(); + at += 1; + byte + }; + let (mut locked, mut narrow, mut repeat) = (false, false, 0u8); + let mut byte = next()?; + loop { + match byte { + 0xf0 => locked = true, + 0x66 => narrow = true, + 0xf2 | 0xf3 => repeat = byte, + // (Of data and stack segments nothing is used; branch hints.) + 0x2e | 0x36 | 0x3e | 0x26 => {} + _ => break, + } + byte = next()?; + } + let mut rex = 0u8; + if byte & 0xf0 == 0x40 { + rex = byte; + byte = next()?; + } + // The vector prefixes, with their own forms of the others. + let vector = match byte { + 0xc5 if rex == 0 => { + let b = next()?; + rex = if b & 0x80 == 0 { 0x44 } else { 0x40 }; + Some(b) + } + 0xc4 if rex == 0 => { + let (b, d) = (next()?, next()?); + if b & 0x1f != 1 { + return None; + } + rex = 0x40 | (!b >> 5 & 7) | (d >> 4 & 8); + Some(d) + } + _ => None, + }; + if let Some(b) = vector { + // (No 32 byte ones: they fill memory.) + if b & 4 != 0 || narrow || repeat != 0 || locked { + return None; + } + // (A store has no third register.) + if b >> 3 & 15 != 15 { + return None; + } + (narrow, repeat) = match b & 3 { + 0 => (false, 0), + 1 => (true, 0), + 2 => (false, 0xf3), + _ => (false, 0xf2), + }; + byte = next()?; + } + let two = vector.is_some() || byte == 0x0f; + if two && vector.is_none() { + byte = next()?; + } + let wide = rex & 8 != 0; + let modrm = next()?; + let (mode, reg, rm) = (modrm >> 6, (modrm >> 3 & 7) as usize | (rex as usize & 4) << 1, modrm & 7); + if mode == 3 { + return None; + } + // The address, all but what hangs on the instruction's length. + let mut address = 0u64; + let mut on_rip = false; + let mut base = Some(rm as usize | (rex as usize & 1) << 3); + if rm == 4 { + let sib = next()?; + let index = (sib >> 3 & 7) as usize | (rex as usize & 2) << 2; + if index != 4 { + address = general(c, index) << (sib >> 6); + } + base = Some((sib & 7) as usize | (rex as usize & 1) << 3); + if sib & 7 == 5 && mode == 0 { + base = None; + } + } else if rm == 5 && mode == 0 { + base = None; + on_rip = true; + } + if let Some(base) = base { + address = address.wrapping_add(general(c, base)); + } + let displacement = match mode { + 1 => i64::from(next()? as i8), + 2 => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])), + _ if base.is_none() => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])), + _ => 0, + }; + address = address.wrapping_add(displacement as u64); + + let words = if wide { + 8 + } else if narrow { + 2 + } else { + 4 + }; + let put = |value: u64| { + let mut bytes = [0; 16]; + bytes[..8].copy_from_slice(&value.to_le_bytes()); + Op::Put(bytes) + }; + let of = |size: usize| Register::of(reg, size, rex != 0); + let vector_bytes = || { + // SAFETY: the registers, whichever way they are named. + let x = unsafe { &c.Anonymous.FltSave }.XmmRegisters[reg]; + let mut bytes = [0; 16]; + bytes[..8].copy_from_slice(&x.Low.to_le_bytes()); + bytes[8..].copy_from_slice(&x.High.to_le_bytes()); + bytes + }; + let alu_of = |kind: u8| match kind { + 0 => Some(Alu::Add), + 1 => Some(Alu::Or), + 4 => Some(Alu::And), + 5 => Some(Alu::Sub), + 6 => Some(Alu::Xor), + _ => None, + }; + let (op, size) = if two { + match (byte, narrow, repeat) { + (0x11, _, 0) | (0x29, _, 0) | (0x7f, true, 0) | (0x7f, false, 0xf3) | (0xe7, true, 0) => (Op::Put(vector_bytes()), 16), + (0x11, false, 0xf3) => (Op::Put(vector_bytes()), 4), + (0x11, false, 0xf2) | (0x13, _, 0) | (0xd6, true, 0) => (Op::Put(vector_bytes()), 8), + (0x17, _, 0) => { + let mut bytes = vector_bytes(); + bytes.copy_within(8.., 0); + (Op::Put(bytes), 8) + } + (0x7e, true, 0) => (Op::Put(vector_bytes()), if wide { 8 } else { 4 }), + _ if vector.is_some() || repeat != 0 => return None, + (0xc3, false, _) => (put(of(words).get(c)), words), + (0xb0 | 0xb1, _, _) => { + let size = if byte & 1 == 0 { 1 } else { words }; + (Op::Cmpxchg(of(size)), size) + } + (0xc0 | 0xc1, _, _) => { + let size = if byte & 1 == 0 { 1 } else { words }; + (Op::Xadd(of(size)), size) + } + _ => return None, + } + } else { + if repeat != 0 { + return None; + } + let size = if byte & 1 == 0 { 1 } else { words }; + let mut constant = |bytes: usize| -> Option { + Some(match bytes { + 1 => next()? as i8 as i64 as u64, + 2 => i64::from(i16::from_le_bytes([next()?, next()?])) as u64, + _ => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])) as u64, + }) + }; + match byte { + 0x88 | 0x89 => (put(of(size).get(c)), size), + 0xc6 | 0xc7 if reg & 7 == 0 => (put(constant(size)?), size), + 0x00 | 0x01 | 0x08 | 0x09 | 0x20 | 0x21 | 0x28 | 0x29 | 0x30 | 0x31 => { + (Op::Alu { alu: alu_of(byte >> 3)?, with: of(size).get(c), keeps: false }, size) + } + 0x80 | 0x81 | 0x83 => { + let alu = alu_of(reg as u8 & 7)?; + (Op::Alu { alu, with: constant(if byte == 0x81 { size } else { 1 })?, keeps: false }, size) + } + 0x86 | 0x87 => { + locked = true; + (Op::Xchg(of(size)), size) + } + 0xfe | 0xff if reg & 7 < 2 => { + (Op::Alu { alu: if reg & 7 == 0 { Alu::Add } else { Alu::Sub }, with: 1, keeps: true }, size) + } + _ => return None, + } + }; + if locked && matches!(op, Op::Put(_)) { + return None; + } + // What is read of memory decides nothing but what is stored: no + // register but the operand is written. + if on_rip { + address = address.wrapping_add(c.Rip).wrapping_add(at as u64); + } + Some(Store { at: address as usize, size, len: at, op, locked }) +} + +const CF: u32 = 1; +const PF: u32 = 4; +const AF: u32 = 0x10; +const ZF: u32 = 0x40; +const SF: u32 = 0x80; +const OF: u32 = 0x800; + +/// The result of an operation on `size` bytes and the flags it leaves. +fn arithmetic(alu: Alu, a: u64, b: u64, size: usize, keeps: bool, flags: u32) -> (u64, u32) { + let m = mask(size); + let (a, b) = (a & m, b & m); + let top = |v: u64| v >> (size * 8 - 1) & 1 != 0; + let r = match alu { + Alu::Add => a.wrapping_add(b), + Alu::Or => a | b, + Alu::And => a & b, + Alu::Sub => a.wrapping_sub(b), + Alu::Xor => a ^ b, + } & m; + let mut out = flags & !(CF | PF | AF | ZF | SF | OF); + let mut flag = |set: bool, flag: u32| out |= if set { flag } else { 0 }; + flag(r == 0, ZF); + flag(top(r), SF); + flag((r as u8).count_ones().is_multiple_of(2), PF); + match alu { + Alu::Add => { + flag(r < a, CF); + flag(top((a ^ r) & (b ^ r)), OF); + flag((a ^ b ^ r) & 16 != 0, AF); + } + Alu::Sub => { + flag(a < b, CF); + flag(top((a ^ b) & (a ^ r)), OF); + flag((a ^ b ^ r) & 16 != 0, AF); + } + _ => {} + } + if keeps { + out = out & !CF | flags & CF; + } + (r, out) +} + +/// A value of `size` bytes in memory, changed by `f` as one if `locked`: what +/// was there (`None`: not aligned). +/// +/// # Safety +/// `size` bytes can be read and written at `at`. +unsafe fn change(at: usize, size: usize, locked: bool, f: impl Fn(u64) -> u64) -> Option { + if !locked { + let mut bytes = [0u8; 8]; + // SAFETY (both): by the caller. + unsafe { std::ptr::copy_nonoverlapping(at as *const u8, bytes.as_mut_ptr(), size) }; + let was = u64::from_le_bytes(bytes); + unsafe { std::ptr::copy_nonoverlapping(f(was).to_le_bytes().as_ptr(), at as *mut u8, size) }; + return Some(was); + } + if !at.is_multiple_of(size) { + return None; + } + // SAFETY (all): by the caller, and aligned. + Some(unsafe { + match size { + 1 => u64::from(AtomicU8::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u8)).ok()?), + 2 => u64::from(AtomicU16::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u16)).ok()?), + 4 => u64::from(AtomicU32::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u32)).ok()?), + _ => AtomicU64::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v))).ok()?, + } + }) +} + +impl Store { + /// Does it, with `to` for the address, and gives the registers what the + /// instruction leaves in them (but the instruction pointer). `false`: + /// nothing was done. + /// + /// # Safety + /// [`Store::size`] bytes can be read and written at `to`. + pub(super) unsafe fn run(&self, c: &mut CONTEXT, to: usize) -> bool { + let (size, locked, m) = (self.size, self.locked, mask(self.size)); + // SAFETY (all `change`s): by the caller. + match self.op { + Op::Put(bytes) => { + // As one, for those the processor stores as one. + // SAFETY (all): by the caller, aligned where it must be. + unsafe { + let low = u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")); + match size { + 1 => (to as *mut u8).write_volatile(bytes[0]), + 2 if to.is_multiple_of(2) => (to as *mut u16).write_volatile(low as u16), + 4 if to.is_multiple_of(4) => (to as *mut u32).write_volatile(low as u32), + 8 if to.is_multiple_of(8) => (to as *mut u64).write_volatile(low), + _ => std::ptr::copy_nonoverlapping(bytes.as_ptr(), to as *mut u8, size), + } + } + } + Op::Alu { alu, with, keeps } => { + let flags = c.EFlags; + let Some(was) = (unsafe { change(to, size, locked, |v| arithmetic(alu, v, with, size, keeps, flags).0) }) else { + return false; + }; + c.EFlags = arithmetic(alu, was, with, size, keeps, flags).1; + } + Op::Xchg(register) => { + let value = register.get(c) & m; + let Some(was) = (unsafe { change(to, size, true, |_| value) }) else { + return false; + }; + register.put(c, was & m, size); + } + Op::Xadd(register) => { + let value = register.get(c); + let Some(was) = (unsafe { change(to, size, locked, |v| v.wrapping_add(value) & m) }) else { + return false; + }; + c.EFlags = arithmetic(Alu::Add, was, value, size, false, c.EFlags).1; + register.put(c, was & m, size); + } + Op::Cmpxchg(register) => { + let (value, expected) = (register.get(c) & m, c.Rax & m); + let Some(was) = (unsafe { change(to, size, locked, |v| if v & m == expected { value } else { v }) }) else { + return false; + }; + let was = was & m; + c.EFlags = arithmetic(Alu::Sub, expected, was, size, false, c.EFlags).1; + if was != expected { + Register { number: 0, high: false }.put(c, was, size); + } + } + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn context() -> CONTEXT { + // SAFETY: plain data. + unsafe { std::mem::zeroed() } + } + + /// The instruction's address, size and length, with every register its + /// number times 0x10000. + fn decoded(code: &[u8]) -> Option<(usize, usize, usize)> { + let mut c = context(); + for n in 0..16 { + *general_mut(&mut c, n) = n as u64 * 0x10000; + } + c.Rip = 0x7000_0000; + let mut padded = code.to_vec(); + padded.resize(15, 0xcc); + store(&padded, &c).map(|s| (s.at, s.size, s.len)) + } + + #[test] + fn stores_are_told_by_their_bytes() { + // mov [rcx+rax+48h], rbx + assert_eq!(decoded(&[0x48, 0x89, 0x5c, 0x01, 0x48]), Some((0x10048, 8, 5))); + // mov [rbx], rdx + assert_eq!(decoded(&[0x48, 0x89, 0x13]), Some((0x30000, 8, 3))); + // or byte [r9+9eh], 1 + assert_eq!(decoded(&[0x41, 0x80, 0x89, 0x9e, 0, 0, 0, 1]), Some((0x9009e, 1, 8))); + // lock dec dword [rcx+10h] + assert_eq!(decoded(&[0xf0, 0xff, 0x49, 0x10]), Some((0x10010, 4, 4))); + // lock xadd [r10+r12*8-1], eax + assert_eq!(decoded(&[0xf0, 0x43, 0x0f, 0xc1, 0x44, 0xe2, 0xff]), Some((0xa0000 + 0xc0000 * 8 - 1, 4, 7))); + // mov word [rsp], 1234h + assert_eq!(decoded(&[0x66, 0xc7, 0x04, 0x24, 0x34, 0x12]), Some((0x40000, 2, 6))); + // mov [rip+10h], al; mov byte [rip+10h], 5 (counted from its end) + assert_eq!(decoded(&[0x88, 0x05, 0x10, 0, 0, 0]), Some((0x7000_0016, 1, 6))); + assert_eq!(decoded(&[0xc6, 0x05, 0x10, 0, 0, 0, 5]), Some((0x7000_0017, 1, 7))); + // mov [12345678h], eax (no base) + assert_eq!(decoded(&[0x89, 0x04, 0x25, 0x78, 0x56, 0x34, 0x12]), Some((0x1234_5678, 4, 7))); + // vmovaps [rsi+10h], xmm4; vmovaps [r12], xmm3; movups [rax], xmm9 + assert_eq!(decoded(&[0xc5, 0xf8, 0x29, 0x66, 0x10]), Some((0x60010, 16, 5))); + assert_eq!(decoded(&[0xc4, 0xc1, 0x78, 0x29, 0x1c, 0x24]), Some((0xc0000, 16, 6))); + assert_eq!(decoded(&[0x44, 0x0f, 0x11, 0x08]), Some((0, 16, 4))); + // vmovss [rax], xmm0; movlps, movhps, vmovq, movd + assert_eq!(decoded(&[0xc5, 0xfa, 0x11, 0x00]), Some((0, 4, 4))); + assert_eq!(decoded(&[0x0f, 0x13, 0x00]), Some((0, 8, 3))); + assert_eq!(decoded(&[0xc5, 0xf9, 0xd6, 0x00]), Some((0, 8, 4))); + assert_eq!(decoded(&[0x66, 0x0f, 0x7e, 0x00]), Some((0, 4, 4))); + // Not stores of these: a 32 byte one, a load, a register's, a string + // instruction, a thread's own memory, a compare, adc. + assert_eq!(decoded(&[0xc5, 0xfc, 0x11, 0x04, 0x31]), None); + assert_eq!(decoded(&[0x48, 0x8b, 0x13]), None); + assert_eq!(decoded(&[0x48, 0x89, 0xd3]), None); + assert_eq!(decoded(&[0xf3, 0xa4]), None); + assert_eq!(decoded(&[0x65, 0x48, 0x89, 0x13]), None); + assert_eq!(decoded(&[0x83, 0x38, 1]), None); + assert_eq!(decoded(&[0x11, 0x00]), None); + // blend by a mask (vmaskmov is of another map), vmovss with a third + // register. + assert_eq!(decoded(&[0xc4, 0xe2, 0x79, 0x2e, 0x00]), None); + } + + /// What the processor makes of `code` with rax as the address, rcx and + /// rdx as operands; against [`Store::run`]. + fn against_the_processor(code: &[u8], seed: u64) { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc}; + static PLACE: std::sync::OnceLock = std::sync::OnceLock::new(); + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: fresh memory for code. + let place = *PLACE.get_or_init(|| unsafe { + VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize + }); + let spread = |n: u64| { + let v = (seed + n).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ seed << 7; + // Small, edge and large ones. + match v >> 61 { + 0 => 0, + 1 => v & 1, + 2 => u64::MAX, + 3 => 0x8000_0000_0000_0000u64 | 0x8000 | 0x80 | 0x8000_0000, + _ => v, + } + }; + // f(address, operand, compared, flags, out): + // mov r11, rcx ; the address (its instruction takes [r11]) + // mov rax, r8 ; mov r10, r9 ; push r10 ; popfq ; ; pushfq ; pop r10 + // mov rcx, [rsp+28h] ; mov [rcx], r10 ; mov [rcx+8], rdx ; mov [rcx+16], rax ; ret + let mut f = vec![0x49, 0x89, 0xcb, 0x4c, 0x89, 0xc0, 0x41, 0x51, 0x9d]; + f.extend(code); + f.extend([0x9c, 0x41, 0x5a, 0x48, 0x8b, 0x4c, 0x24, 0x28]); + f.extend([0x4c, 0x89, 0x11, 0x48, 0x89, 0x51, 0x08, 0x48, 0x89, 0x41, 0x10, 0xc3]); + type F = unsafe extern "system" fn(*mut u64, u64, u64, u64, *mut [u64; 3]); + let (there, operand, compared) = (spread(1), spread(2), if seed % 3 == 0 { spread(1) } else { spread(3) }); + let flags = 0x202 | (spread(4) & 0x8d5) as u32; + let (mut memory, mut out) = (there, [0; 3]); + // SAFETY: the code above, which keeps to the calling convention. + unsafe { + std::ptr::copy_nonoverlapping(f.as_ptr(), place as *mut u8, f.len()); + let f: F = std::mem::transmute(place); + f(&mut memory, operand, compared, u64::from(flags), &mut out); + } + let mut c = context(); + let mut ours = there; + (c.R11, c.Rdx, c.Rax, c.EFlags) = (&raw mut ours as u64, operand, compared, flags); + let mut padded = code.to_vec(); + padded.resize(15, 0xcc); + let store = store(&padded, &c).unwrap_or_else(|| panic!("{code:x?}")); + assert_eq!((store.at, store.len), (&raw mut ours as usize, code.len()), "{code:x?}"); + // SAFETY: our word. + assert!(unsafe { store.run(&mut c, &raw mut ours as usize) }); + assert_eq!(ours, memory, "{code:x?} of {there:x} with {operand:x}"); + assert_eq!((c.Rdx, c.Rax), (out[1], out[2]), "{code:x?} of {there:x} with {operand:x}, {compared:x}"); + // (`and`, `or` and `xor` leave AF as they like.) + const SEEN: u32 = CF | PF | ZF | SF | OF; + assert_eq!(c.EFlags & SEEN, out[0] as u32 & SEEN, "{code:x?} of {there:x} with {operand:x}"); + } + + #[test] + fn stores_do_what_the_processor_does() { + let mut codes: Vec> = Vec::new(); + // op [r11], rdx in all sizes; op [r11], constant; inc, dec; xchg, xadd, cmpxchg. + for op in [0x00, 0x08, 0x20, 0x28, 0x30, 0x88, 0x86] { + codes.push(vec![0x41, op, 0x13]); + codes.push(vec![0x66, 0x41, op | 1, 0x13]); + codes.push(vec![0x41, op | 1, 0x13]); + codes.push(vec![0x49, op | 1, 0x13]); + if op < 0x80 { + codes.push(vec![0xf0, 0x41, op | 1, 0x13]); + codes.push(vec![0xf0, 0x49, op | 1, 0x13]); + } + } + for kind in [0u8, 1, 4, 5, 6] { + let modrm = 0x03 | kind << 3; + for constant in [1, 0x7f, 0x80, 0xff] { + codes.push(vec![0x41, 0x80, modrm, constant]); + codes.push(vec![0x41, 0x83, modrm, constant]); + codes.push(vec![0x49, 0x83, modrm, constant]); + codes.push(vec![0x66, 0x41, 0x83, modrm, constant]); + codes.push(vec![0xf0, 0x41, 0x83, modrm, constant]); + codes.push(vec![0x49, 0x81, modrm, 3, 0, 0, constant]); + codes.push(vec![0x66, 0x41, 0x81, modrm, 3, constant]); + } + } + for modrm in [0x03, 0x0b] { + codes.push(vec![0x41, 0xfe, modrm]); + codes.push(vec![0x41, 0xff, modrm]); + codes.push(vec![0x49, 0xff, modrm]); + codes.push(vec![0xf0, 0x41, 0xff, modrm]); + codes.push(vec![0x66, 0x41, 0xff, modrm]); + } + for op in [0xb0, 0xc0] { + codes.push(vec![0x41, 0x0f, op, 0x13]); + codes.push(vec![0xf0, 0x41, 0x0f, op, 0x13]); + codes.push(vec![0xf0, 0x66, 0x41, 0x0f, op | 1, 0x13]); + codes.push(vec![0xf0, 0x41, 0x0f, op | 1, 0x13]); + codes.push(vec![0xf0, 0x49, 0x0f, op | 1, 0x13]); + } + codes.push(vec![0x41, 0xc6, 0x03, 0x99]); + codes.push(vec![0x66, 0x41, 0xc7, 0x03, 0x99, 0x88]); + codes.push(vec![0x41, 0xc7, 0x03, 1, 2, 3, 0x84]); + codes.push(vec![0x49, 0xc7, 0x03, 1, 2, 3, 0x84]); + for code in &codes { + for seed in 0..200 { + against_the_processor(code, seed); + } + } + } + + /// The second byte of a register, and 32 bits that clear the rest. + #[test] + fn registers_are_read_and_written_as_by_the_processor() { + let mut c = context(); + c.Rax = 0x1122_3344_5566_7788; + assert_eq!(Register::of(4, 1, false).get(&c) & 0xff, 0x77, "ah"); + assert_eq!(Register::of(4, 1, true), Register { number: 4, high: false }, "spl"); + Register { number: 0, high: true }.put(&mut c, 0xff, 1); + assert_eq!(c.Rax, 0x1122_3344_5566_ff88); + Register { number: 0, high: false }.put(&mut c, 0xabcd, 2); + assert_eq!(c.Rax, 0x1122_3344_5566_abcd); + Register { number: 0, high: false }.put(&mut c, u64::MAX, 4); + assert_eq!(c.Rax, 0xffff_ffff); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 7d98205..1c790d2 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -791,19 +791,36 @@ impl Bits { unsafe { piece.as_ref() } } - /// One caller at a time (under the guards' lock). fn set(&self, block: usize) { - use std::sync::atomic::Ordering::{Relaxed, Release}; + use std::sync::atomic::Ordering::{AcqRel, Acquire, SeqCst}; let word = block / 64; let Some(place) = self.0.get(word / Bits::WORDS) else { return; }; - if place.load(Relaxed).is_null() { + if place.load(Acquire).is_null() { let piece: Box = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]); - place.store(Box::into_raw(piece), Release); + let piece = Box::into_raw(piece); + if place.compare_exchange(std::ptr::null_mut(), piece, AcqRel, Acquire).is_err() { + // SAFETY: made just now, and another thread's is there. + drop(unsafe { Box::from_raw(piece) }); + } } if let Some(piece) = self.piece(word) { - piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release); + piece[word % Bits::WORDS].fetch_or(1 << (block % 64), SeqCst); + } + } + + /// Sixty-four of them. + fn word(&self, word: usize) -> u64 { + self.piece(word).map_or(0, |piece| piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst)) + } + + /// Whether it was set, and is no more. + fn take(&self, block: usize) -> bool { + self.any(block, block + 1) && { + let (word, bit) = (block / 64, 1 << (block % 64)); + self.piece(word) + .is_some_and(|piece| piece[word % Bits::WORDS].fetch_and(!bit, std::sync::atomic::Ordering::SeqCst) & bit != 0) } } @@ -883,12 +900,93 @@ static PUBLISHED: Bits = Bits::new(); /// no view. static PROTECTED: Bits = Bits::new(); +/// The blocks the title's bytes were put in beside their guards +/// ([`put_beside`]) and that no asking has told as written since. Such a +/// block is as it was else: read-only, clean, and an asking that finds its +/// bit here takes the bit and tells it as written. +/// +/// The bit is set when the bytes are in, at every view of the page, and +/// [`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. +static BESIDE: Bits = Bits::new(); + +/// 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]; + +fn put_count(block: usize) -> &'static std::sync::atomic::AtomicU32 { + &PUT[block % PUT.len()] +} + +/// Whether [`put_beside`] put it there. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Beside { + Done, + /// The block has had its share. + Full, + /// Not guarded, or there is no other way to its page, or the runtime is + /// changing a mapping. + Cannot, +} + +/// Whether a block of `[at, at + len)` is (or is about to be) read-only by +/// our hand. `len` is not 0. +#[inline] +pub(crate) fn guards_any(at: usize, len: usize) -> bool { + PROTECTED.any(at / BLOCK, (at.saturating_add(len) - 1) / BLOCK + 1) +} + +/// The title's bytes for a guarded block, put in by `put` at our own view of +/// the same page: it is given what to add to an address of the block (as by +/// `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) { + return Beside::Cannot; + } + let count = put_count(block); + if count.load(Relaxed) + weight > crate::titlewrite::MOST { + return Beside::Full; + } + // No mapping changes until all is told: a view of the page that came + // after the look at them would not be. + let Some(_reading) = title_memory_reading_now() else { + return Beside::Cannot; + }; + let Some((page, shown)) = crate::inplace::beside_page(block * BLOCK) else { + return Beside::Cannot; + }; + put(page.wrapping_sub(block * BLOCK)); + count.fetch_add(weight, Relaxed); + for view in shown.iter().filter(|&&view| view != 0) { + BESIDE.set(view / BLOCK); + } + for view in shown.iter().filter(|&&view| view != 0) { + PUBLISHED.clear(view / BLOCK); + } + Beside::Done +} + +/// The title is about to write block by block around `at`: as by a fault. +pub(crate) fn opened_for_writing(at: usize) { + let mut g = guards(); + if open(&mut g, at, at + 1) != 0 { + g.opened(at / BLOCK); + } +} + /// An asking made blocks of `pages` clean and noted them in the journal. fn publish(pages: &[usize]) { let g = guards(); - for page in pages { - if g.clean.contains(*page) || g.held.contains(*page) { - PUBLISHED.set(*page); + for &page in pages { + if g.clean.contains(page) || g.held.contains(page) { + 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) { + PUBLISHED.clear(page); + } } } } @@ -1240,6 +1338,7 @@ impl Guards { self.opened.clear(); } } + put_count(block).store(0, std::sync::atomic::Ordering::Relaxed); self.opened.insert(block, std::time::Instant::now()); } } @@ -1434,7 +1533,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 { + if g.clean.range(first..last).count() == last - first && !BESIDE.any(first, last) { // Nothing written, mapped or new since the range was last taken. #[cfg(feature = "diagnostics")] tally(3, 1); @@ -1471,7 +1570,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) | g.absent.word(word); + 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)); } let mut run: Option<(usize, usize)> = None; @@ -1486,12 +1585,20 @@ fn guard(start: usize, end: usize) -> Option> { drop(g); g = guards_timed(); } + // 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); + } if g.protected.contains(block) { // Read-only by way of another view of its page, or not clean - // because one could not be made so. + // because one could not be made so. (Or clean, and bytes were put + // in beside the guard: it stays.) if let Some((from, to)) = run.take() { protect(&mut g, from, to); } + if g.clean.contains(block) { + continue; + } if cover(&mut g, block, block + 1) { g.clean.insert(block); } @@ -2330,9 +2437,11 @@ pub(crate) fn install() { // A fault of our own copies (`crate::safecopy`): whatever it is, if // it is not a block we guard, the copy fails and goes on from there. let ours = crate::safecopy::failing_exit(r.ExceptionAddress as usize); - let fail = |exit: usize| { + // SAFETY: as above. + let context = unsafe { (*info).ContextRecord }; + let fail = move |exit: usize| { // SAFETY: the context the system passes, to go on from. - unsafe { (*(*info).ContextRecord).Rip = exit as u64 }; + unsafe { (*context).Rip = exit as u64 }; EXCEPTION_CONTINUE_EXECUTION }; if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS @@ -2353,6 +2462,13 @@ pub(crate) fn install() { } let at = r.ExceptionInformation[1]; let block = at / BLOCK; + if ours.is_none() + && PROTECTED.any(block, block + 1) + // SAFETY: the context the system passes, to go on from. + && crate::titlewrite::store(unsafe { &mut *context }, at) + { + return EXCEPTION_CONTINUE_EXECUTION; + } // 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 @@ -2380,6 +2496,7 @@ pub(crate) fn install() { let ns = waited.as_nanos().min(u128::from(u32::MAX)) as usize; let held = (began.elapsed() - waited).as_nanos() as u64; 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); } return EXCEPTION_CONTINUE_EXECUTION; } @@ -3308,6 +3425,116 @@ mod tests { drop_views(section, &[one, two], BLOCK); } + /// What is put in beside a guard is told at every view, once, and the + /// block stays read-only; until it has had its share. + #[test] + fn what_the_title_puts_in_beside_a_guard_is_told() { + let (section, one, two) = two_views(BLOCK); + crate::title_memory_section(section, BLOCK as u64, true); + let page = |view: usize| view / PAGE; + for view in [one, two] { + assert_eq!(guard(view, view + BLOCK), Some(vec![page(view)])); + } + assert!(writes(one, one + BLOCK, true).is_some() && writes(two, two + BLOCK, true).is_some()); + put_count(one / BLOCK).store(0, std::sync::atomic::Ordering::Relaxed); + let put = |byte: u8| loop { + // SAFETY: a byte of the section's only page. + let done = put_beside(one / BLOCK, 1, |delta| unsafe { ((one + 100).wrapping_add(delta) as *mut u8).write(byte) }); + // (Other tests hold changes of mapping.) + if done != Beside::Cannot { + return done; + } + }; + for round in 1..4 { + assert_eq!(put(round), Beside::Done); + // SAFETY: the view the title reads it by. + assert_eq!(unsafe { ((two + 100) as *const u8).read_volatile() }, round); + assert!(!writable(one) && !writable(two) && !published(one, one + BLOCK) && !published(two, two + BLOCK)); + for view in [two, one] { + assert_eq!(guard(view, view + BLOCK), Some(vec![page(view)])); + assert_eq!(guard(view, view + BLOCK), Some(Vec::new())); + } + } + for _ in 0..crate::titlewrite::MOST { + assert_eq!(put(9), Beside::Done); + } + assert_eq!(put(9), Beside::Full); + // A refresh between gives it its share again. + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + assert_eq!(put(9), Beside::Done); + // Opened by a fault, it is told by that. + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + // SAFETY: a view, opened by the handler. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(put_beside(one / BLOCK, 1, |_| panic!("it is not guarded")), Beside::Cannot); + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + drop_views(section, &[one, two], BLOCK); + crate::title_memory_section_gone(section); + } + + /// Stores that fault, and copies, as the title makes them: what is there + /// after, the block's guard and what the next asking says. + #[test] + fn stores_and_copies_of_the_title_leave_the_guard() { + use std::sync::atomic::{AtomicU32, Ordering}; + unsafe extern "system-unwind" fn real(to: *mut u8, from: *const u8, n: usize) -> *mut u8 { + // SAFETY: by the caller. + unsafe { std::ptr::copy(from, to, n) }; + to + } + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + crate::title_memory_section(section, SIZE as u64, true); + let pages = |view: usize| vec![view / PAGE, view / PAGE + 1]; + assert_eq!(guard(one, one + SIZE), Some(pages(one))); + assert_eq!(guard(two, two + SIZE), Some(pages(two))); + let copy = crate::titlewrite::import("memcpy", real as *const () as usize); + crate::titlewrite::ON_IN_TEST.set(true); + let copy = if copy == real as *const () as usize { + crate::titlewrite::copy_for_test(real as *const () as usize) + } else { + copy + }; + // SAFETY: of that signature. + let copy: unsafe extern "system-unwind" fn(*mut u8, *const u8, usize) -> *mut u8 = unsafe { std::mem::transmute(copy) }; + // No change of mapping meanwhile but the other tests' moments of it: + // a store that meets one opens the block, as before. + let mut kept = 0; + let quiet = || { + while title_memory_reading_now().is_none() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + for round in 1..200u32 { + quiet(); + // SAFETY (all): words of the view. + unsafe { ((one + 64) as *mut u32).write_volatile(round) }; + let was = unsafe { AtomicU32::from_ptr((two + 64) as *mut u32) }.fetch_sub(1, Ordering::SeqCst); + assert_eq!((was, unsafe { ((one + 64) as *const u32).read_volatile() }), (round, round - 1)); + let bytes = vec![round as u8; 3000 + round as usize]; + // Over the end of the first block. + assert_eq!(unsafe { copy((one + BLOCK - 1000) as *mut u8, bytes.as_ptr(), bytes.len()) } as usize, one + BLOCK - 1000); + let there = unsafe { std::slice::from_raw_parts((two + BLOCK - 1000) as *const u8, bytes.len()) }; + assert!(there == bytes && unsafe { ((two + BLOCK + 2000 + round as usize) as *const u8).read_volatile() } != round as u8); + kept += usize::from(!writable(one) && !writable(two)); + for view in [one, two] { + assert_eq!(guard(view, view + SIZE), Some(pages(view)), "round {round}"); + assert_eq!(guard(view, view + SIZE), Some(Vec::new()), "round {round}"); + } + } + assert!(kept > 10, "the guard stayed {kept} times: {:?}", crate::titlewrite::DONE); + // Many stores to a block: it is opened. + quiet(); + for k in 0..20 { + unsafe { ((one + 128 + k * 4) as *mut u32).write_volatile(7) }; + } + assert!(writable(one)); + crate::titlewrite::ON_IN_TEST.set(false); + drop_views(section, &[one, two], SIZE); + crate::title_memory_section_gone(section); + } + /// The set of blocks against another of the same. #[test] fn blocks_are_a_set() { @@ -3604,6 +3831,7 @@ mod many_askers_tests { }; let by_bits = std::sync::atomic::AtomicUsize::new(0); let past = std::sync::atomic::AtomicUsize::new(0); + let title_beside = std::sync::atomic::AtomicUsize::new(0); std::thread::scope(|s| { if VIEWS > 1 { s.spawn(move || { @@ -3635,7 +3863,7 @@ mod many_askers_tests { }); } for t in 0..THREADS { - let (by_bits, past) = (&by_bits, &past); + let (by_bits, past, title_beside) = (&by_bits, &past, &title_beside); s.spawn(move || { super::REST_IN_TEST.set(rest); let mut last = [[0u64; PAGES]; VIEWS]; @@ -3657,6 +3885,21 @@ mod many_askers_tests { let word = through + page * PAGE + t * 8; // SAFETY (both): as above. // (Waited for: other tests hold changes of mapping.) + // (Some as a copy of the title's, or a store of it, does.) + if next(3) == 0 + && super::put_beside(word / PAGE, 1, |delta| unsafe { + (word.wrapping_add(delta) as *mut u64).write_volatile(3); + }) == super::Beside::Done + { + title_beside.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); + let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1); + assert!(number > last[page], "page {page}, beside: {number} is not after {}", last[page]); + for l in &mut last[from..to] { + *l = now; + } + continue; + } let reading = (next(3) == 0).then(super::title_memory_reading); let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); if let Some(to) = beside { @@ -3694,6 +3937,7 @@ mod many_askers_tests { }); assert!(by_bits.into_inner() > 0, "the bits answered none"); assert!(past.into_inner() > 0, "nothing was put past the guards"); + assert!(title_beside.into_inner() > 0, "nothing of the title's was put in beside the guards"); // (The view stays: at its address other tests' memory would be told // of these writes.) } diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 3c217d8..5199821 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -79,6 +79,14 @@ impl HostPolicy { return None; } let address = imp::resolve(dll, symbol)?; + // The title's copies of memory look where they write. + #[cfg(windows)] + if let ImportSymbol::Name { name, .. } = symbol { + let ours = victory_gpu::titlewrite::import(name, address); + if ours != address { + return Some(ours); + } + } // With a timeline asked for, what threads wait with is wrapped. #[cfg(all(windows, feature = "diagnostics"))] if let ImportSymbol::Name { name, .. } = symbol { From adf57069830391af2d2e33c9b04f50dc6ab1615c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:57:50 -0600 Subject: [PATCH 20/31] Structure builder: accesses stay near the root views, a size that cannot be one counts as none (VICTORY_BVH_BOUNDS=0: neither) A structure that was written over names gigabytes; the builder's copy of it (CopyForBVHUpdate, 63 a frame in the dorm, 13.3 of 84 ms in the timing run light-13) went through all other structures' memory. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/shader_cache.rs | 1 + crates/victory-shader/src/emit/lower.rs | 30 +++++++++++++++++++++++-- crates/victory-shader/src/emit/mod.rs | 9 ++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 35b5446..016ab4e 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -74,6 +74,7 @@ fn build() -> [u8; 32] { "VICTORY_STRICT_JOINS", "VICTORY_MESH_OUTPUT_STRICT", "VICTORY_BVH_FENCES", + "VICTORY_BVH_BOUNDS", ] { bytes.extend_from_slice(name.as_bytes()); bytes.push(b'='); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ecad742..09db9d1 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -3184,7 +3184,19 @@ impl<'a> Lower<'a> { let k31 = self.s.m.i32(31); let sign = self.s.m.bin(c, Bin::AShr, off, k31); let hi = self.s.m.bin(c, Bin::Add, hi, carry); - let hi = self.s.m.bin(c, Bin::Add, hi, sign); + let mut hi = self.s.m.bin(c, Bin::Add, hi, sign); + let mut sum = sum; + if super::builder_bounds() { + // No structure is near 64 MiB (the greatest seen has 14). One + // whose memory was written over says it has gigabytes, and the + // builder's copy of it went through all other structures' memory + // after it and, past 2 GiB, before it. Nothing is there instead. + let (below, all, zero) = (self.s.m.i32(16 << 20), self.s.m.i32(80 << 20), self.s.m.i32(0)); + let at = self.s.m.bin(c, Bin::Add, off, below); + let near = self.s.m.cmp(c, pred::IULT, at, all); + sum = self.s.m.select(c, near, sum, zero); + hi = self.s.m.select(c, near, hi, zero); + } let (h, byte) = self.memory(sum, hi, guard, store); self.root_copy = Some(h); Some((h, byte)) @@ -6086,9 +6098,18 @@ impl<'a> Lower<'a> { return Ok(()); } if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { + // The size in a structure's header (its second dword), which a + // copy of it loops over. + let size = *offset == 4 + && count == 1 + && extra.is_none() + && matches!(soffset, Operand::Scalar { code: NULL, .. }) + && super::builder_bounds(); + let mut root = false; let h = match self.root_memory(src, addr, None, false) { Some((h, byte)) => { addr = byte; + root = true; h } None => self.handle(site, src, false, (11, 0))?, @@ -6108,7 +6129,12 @@ impl<'a> Lower<'a> { &[h, a, u, mask, al], ); let x = self.s.m.extract(c, r, 0); - let x = self.as_int(x); + let mut x = self.as_int(x); + if size && root { + let (most, zero) = (self.s.m.i32(1 << 20), self.s.m.i32(0)); + let sane = self.s.m.cmp(c, pred::IULT, x, most); + x = self.s.m.select(c, sane, x, zero); + } self.write(inst, Reg::S(code + k as u8), x, None); } return Ok(()); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b714dc6..eed0fac 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -188,6 +188,15 @@ pub fn builder_fences() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_FENCES").is_none_or(|v| v != "0")) } +/// Whether the structure builder's accesses through its root views stay near +/// them, and a size in a structure's header that cannot be one counts as none +/// (`VICTORY_BVH_BOUNDS=0`: neither). Part of the translation: the shader +/// cache keys on it. +pub fn builder_bounds() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_BOUNDS").is_none_or(|v| v != "0")) +} + /// The clean-up passes that run over a translated program before it is /// written (`bitcode::opt`): a set of that module's pass bits. Every pass /// is exact, so the switch is for telling a translator fault from a From e4d08379d9a2c4d4a0e3fd4f210be082cacb029e Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:57:55 -0600 Subject: [PATCH 21/31] A flipped slot's quick record is forgotten Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor/host.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 6470155..53d6f81 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2193,6 +2193,7 @@ impl HostHeap { self.put(f.index); #[cfg(feature = "diagnostics")] let was = shown; + self.quick_is(f.index, 0); self.made.set(f.index, f.key); self.keep(f.index, kept); #[cfg(feature = "diagnostics")] From e162982e2d1fc0d516c1ec0f456c64285c567bc5 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 12:59:04 -0600 Subject: [PATCH 22/31] What a landing put into title memory is not sent up again (VICTORY_LAND_ECHO=0: sent) Memory the kernel watches counts as written by the landing of what shaders wrote; the next refresh copied those pages and sent them up again (run submit-2, the dorm: a copy of 90 MB, write-combined for the title, 14.9 MB a frame fetched and 14.4 MB of the same pieces sent). Pages a landing was noted in are compared with the CPU side, 4 KiB at a time, and left if they are alike. Not run in the game yet. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/traffic.rs | 6 + crates/victory-gpu/src/shadow.rs | 157 +++++++++++++++++++++++++ 2 files changed, 163 insertions(+) diff --git a/crates/victory-gpu/src/host/traffic.rs b/crates/victory-gpu/src/host/traffic.rs index 92a003c..4477164 100644 --- a/crates/victory-gpu/src/host/traffic.rs +++ b/crates/victory-gpu/src/host/traffic.rs @@ -39,6 +39,12 @@ pub(super) fn line(frames: f64) { let sum = |way: usize| all.iter().map(|(_, m)| m.bytes[way]).sum::(); // Copies that only move one way. let only = |way: usize| all.iter().filter(|(_, m)| m.bytes[1 - way] == 0).map(|(_, m)| m.bytes[way]).sum::(); + tracing::info!( + "landings in title memory looked at by refreshes per frame (VICTORY_LAND_ECHO=0: sent up): {:.1} MB held already and left, \ + {:.1} MB the title's too", + mb(crate::shadow::ECHO[0].swap(0, std::sync::atomic::Ordering::Relaxed)), + mb(crate::shadow::ECHO[1].swap(0, std::sync::atomic::Ordering::Relaxed)), + ); tracing::info!( "bytes of host copies over the bus per frame: {:.1} MB up ({:.1} of copies nothing was fetched from), {:.1} MB fetched \ ({:.1} of copies nothing was sent up to), {} copies; the most:", diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 671d6d8..874d549 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -26,6 +26,12 @@ use crate::watch::PAGE; /// A title buffer's host copy. pub(crate) struct Shadow { + /// Title memory's pages of 4 KiB (from the one `start` lies in on), a bit + /// each, that what shaders wrote was put into since a refresh last looked + /// at them ([`Shadow::take_landed`]); empty until then. + landings: Mutex>, + /// Whether any is. + landing: std::sync::atomic::AtomicBool, /// The bytes of `buffer`, once asked. width: std::sync::OnceLock, pub(crate) buffer: ID3D12Resource, @@ -1949,6 +1955,29 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } +/// The kernel's page. +const KERNEL_PAGE: usize = 4096; + +/// Whether a refresh looks if what counts as written is only what a landing +/// put there, and then sends nothing of it up (`VICTORY_LAND_ECHO=0`: it copies +/// and sends it, as before). +/// +/// What shaders wrote comes down, goes into title memory and into the CPU's +/// side of the copy alike. In memory the kernel watches that is a write like +/// any other (it cannot be told as the guards' blocks can, `crate::land`), and +/// the next refresh of it copied the pages and sent them up again: in the dorm +/// 14.4 MB a frame of one copy of 90 MB whose 263 pieces were all fetched and +/// all sent, 28 of 72 MB over the bus in all (run submit-2). Only pages a +/// landing was noted in are compared, 4 KiB at a time: a page that is not the +/// same goes up whole, as before, and so does every other. +fn land_echo() -> bool { + crate::toggled!("VICTORY_LAND_ECHO") +} + +/// Since the last frame-rate line: bytes found to be a landing's alone, and +/// bytes a landing was noted in that were the title's too. +pub(crate) static ECHO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + /// Whether a refresh of a copy in the card's memory takes, and sends up, /// the dwords that title memory changed and no others /// (`VICTORY_SEND_CHANGED=1`; off: the 64 KiB pages written since it last @@ -2479,6 +2508,49 @@ fn by_parts(runs: Vec<(usize, usize, bool)>, pages: &[(usize, u64)], parts: &[u1 out } +#[cfg(test)] +mod landing_tests { + use super::{KERNEL_PAGE, Shadow}; + + /// A page that only a landing wrote is not sent up again; one the title + /// wrote too is, and so is every page no landing was noted in. + #[test] + fn what_a_landing_wrote_is_not_sent_up_again() { + const PAGES: usize = 6; + let room = vec![7u8; (PAGES + 1) * KERNEL_PAGE]; + let title = room.as_ptr() as usize; + let title = title.next_multiple_of(KERNEL_PAGE); + let mut side = vec![7u8; PAGES * KERNEL_PAGE]; + let copy = Shadow::unbacked(title as u64, side.as_mut_ptr(), side.len() as u64, true); + let write = |page: usize| { + // SAFETY: in `room`. + unsafe { ((title + page * KERNEL_PAGE + 9) as *mut u8).write_volatile(8) } + }; + let page = |from: usize, to: usize| (title + from * KERNEL_PAGE, title + to * KERNEL_PAGE); + copy.note_landing(KERNEL_PAGE, 4 * KERNEL_PAGE); + // Page 2: the title's too. + write(2); + let (from, to) = page(0, 6); + copy.take_landed(from, to); + let mut dirty = copy.take_dirty(); + dirty.sort_unstable(); + let part = |a: usize, b: usize| (a * KERNEL_PAGE, b * KERNEL_PAGE); + assert_eq!(super::joined(dirty), [part(0, 1), part(2, 3), part(4, 6)]); + assert_eq!(side[2 * KERNEL_PAGE + 9], 8); + // Looked at: from here on as any other. + let (from, to) = page(1, 2); + copy.take_landed(from, to); + assert_eq!(copy.take_dirty(), [part(1, 2)]); + // In part: looked at again when the rest is. + copy.note_landing(3 * KERNEL_PAGE, 3 * KERNEL_PAGE + 1); + let (from, to) = page(3, 4); + copy.take_landed(from, from + 100); + copy.take_landed(from, to); + assert_eq!(copy.take_dirty(), []); + drop(room); + } +} + #[cfg(test)] mod parts_tests { use super::{PAGE, by_parts}; @@ -2754,6 +2826,8 @@ impl Shadow { LIVE[0].fetch_add(1, Ordering::Relaxed); LIVE[1].fetch_add(len, Ordering::Relaxed); Shadow { + landings: Mutex::default(), + landing: Default::default(), width: Default::default(), buffer, data, @@ -3667,6 +3741,83 @@ impl Shadow { bytes } + /// What shaders wrote in `[from, to)` (offsets) was put into title memory. + fn note_landing(&self, from: usize, to: usize) { + let first = self.start as usize / KERNEL_PAGE; + let pages = (self.start as usize + from) / KERNEL_PAGE - first..(self.start as usize + to).div_ceil(KERNEL_PAGE) - first; + let mut bits = self.landings.lock().unwrap_or_else(|e| e.into_inner()); + if bits.is_empty() { + let all = (self.start + self.len).div_ceil(KERNEL_PAGE as u64) as usize - first; + bits.resize(all.div_ceil(64), 0); + } + for page in pages { + bits[page / 64] |= 1 << (page % 64); + } + self.landing.store(true, Ordering::Release); + } + + /// [`Shadow::take`] of `[from, to)`, which the copy held before and which + /// is written since: where it may be only the landing that wrote it, the + /// 4 KiB that title memory and the CPU's side have alike are left as they + /// are, and nothing of them is sent ([`land_echo`]). + fn take_landed(&self, from: usize, to: usize) -> usize { + thread_local! { + static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let start = self.start as usize; + let first = start / KERNEL_PAGE; + // Runs of pages noted, and not noted (any more). + let mut runs: Vec<(usize, usize, bool)> = Vec::new(); + { + let mut bits = self.landings.lock().unwrap_or_else(|e| e.into_inner()); + let mut at = from; + while at < to { + let next = ((at / KERNEL_PAGE + 1) * KERNEL_PAGE).min(to); + let page = at / KERNEL_PAGE - first; + let noted = bits.get(page / 64).is_some_and(|word| word >> (page % 64) & 1 != 0); + // (A page looked at in part is looked at again.) + if noted && next - at == KERNEL_PAGE { + bits[page / 64] &= !(1 << (page % 64)); + } + match runs.last_mut() { + Some(last) if last.2 == noted && next - last.0 <= PAGE => last.1 = next, + _ => runs.push((at, next, noted)), + } + at = next; + } + } + TITLE.with_borrow_mut(|title| { + for (from, to, noted) in runs { + if !noted { + self.copy(from, to); + continue; + } + title.resize(to - from, 0); + // (Pages that are not there read as zeros.) + crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, to - from, false); + let mut at = from; + while at < to { + let next = ((at / KERNEL_PAGE + 1) * KERNEL_PAGE).min(to); + let title = &title[at - from..next - from]; + // SAFETY: inside the mapping of the copy's CPU side, which + // nothing else reads or writes there: no shader's range + // holds it, and the parts of a refresh lie apart. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), next - at) }; + if title == held { + ECHO[0].fetch_add((next - at) as u64, Ordering::Relaxed); + } else { + ECHO[1].fetch_add((next - at) as u64, Ordering::Relaxed); + held.copy_from_slice(title); + self.changed(at - start, next - start); + self.card_changed(at - start, next - start); + } + at = next; + } + } + }); + to - from + } + /// Copies title memory `[from, to)` (inside the buffer) into the copy; /// `known`: the copy held it before ([`send_changed`]). fn take(&self, from: usize, to: usize, known: bool) -> usize { @@ -3675,6 +3826,9 @@ impl Shadow { static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else { + if known && self.card.is_some() && self.landing.load(Ordering::Acquire) && land_echo() && !crate::host::upcheck::on() { + return self.take_landed(from, to); + } return self.copy(from, to); }; let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); @@ -4134,6 +4288,9 @@ impl Shadow { let merged = unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) }; self.walls_merged(hi - lo, merged as usize); + if merged > 0 { + self.note_landing(lo, hi); + } put += merged; } put From 83a1bcf5b7d5d446ce8af1d97704ed29feaaa5e9 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:10:05 -0600 Subject: [PATCH 23/31] Writes of the title's that change nothing are not made: faulting stores and copies beside the guards, and flags it sets that are set (VICTORY_WRITE_SITES=: places changed at load to look first; off without it) A store that faults, or a part of a copy into a guarded block, whose bytes are there already is left out (with VICTORY_STORE_BESIDE, VICTORY_COPY_BESIDE). The places in the title's code where that is the rule and the instruction is an `or` of a byte with a constant are written into the file, and made to look before they write at the next start. The file holds offsets, no code. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/run.rs | 5 + crates/victory-gpu/src/copystat.rs | 8 +- crates/victory-gpu/src/titlewrite.rs | 129 +++++++++- crates/victory-gpu/src/titlewrite/decode.rs | 32 +++ crates/victory-gpu/src/watch.rs | 18 ++ crates/victory-loader/src/console_insn.rs | 6 +- crates/victory-loader/src/lib.rs | 2 + crates/victory-loader/src/write_sites.rs | 255 ++++++++++++++++++++ 8 files changed, 437 insertions(+), 18 deletions(-) create mode 100644 crates/victory-loader/src/write_sites.rs diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 0d05390..0c7bf46 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -162,6 +162,11 @@ pub fn run( } let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); show(&exe_name, image.bind_imports(&with_dlls, policy)?); + if execute { + let (name, size) = (prepared.file_name(), image.info().size_of_image as usize); + // SAFETY: the image stays mapped, and nothing of it has run yet. + unsafe { victory_loader::write_sites::apply_asked(&name, image.base(), size) }; + } if !execute { println!("not executing (pass --execute to start the title)"); return Ok(()); diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 6fa7971..100949b 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1203,11 +1203,13 @@ pub(crate) fn log(frames: f64) { "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" ); - let [copies, blocks, opened, stores, unknown, full] = - [0, 1, 2, 3, 4, 5].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); + let [copies, blocks, opened, stores, unknown, full, stayed, copied_same] = + [0, 1, 2, 3, 4, 5, 6, 7].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); tracing::info!( "the title's writes beside the guards, since the start: {copies} copies (VICTORY_COPY_BESIDE=1), {blocks} blocks, {opened} opened; \ - {stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many" + {stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies; \ + the busiest stores (left out/changed): {}", + crate::titlewrite::busiest() ); // Where the wall clock of a frame goes: the phases of a frame, the // processor time of the whole process, and what each submitting and diff --git a/crates/victory-gpu/src/titlewrite.rs b/crates/victory-gpu/src/titlewrite.rs index 08aee3a..1a551c5 100644 --- a/crates/victory-gpu/src/titlewrite.rs +++ b/crates/victory-gpu/src/titlewrite.rs @@ -32,8 +32,9 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; /// Diagnostics, since the start: copies of the title's that put bytes beside /// the guards, blocks they did so in, blocks they opened instead; stores done /// beside the guards, faulting stores not understood, and blocks opened -/// because too many came. -pub(crate) static DONE: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; +/// because too many came; stores and parts of copies that left the memory as +/// it was, and were not made. +pub(crate) static DONE: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; fn add(what: usize) { DONE[what].fetch_add(1, Relaxed); @@ -141,7 +142,11 @@ unsafe fn copied(to: *mut u8, from: *const u8, n: usize, real: usize) -> *mut u8 // SAFETY: by the caller. return unsafe { real(to, from, n) }; } - in_pieces(to as usize, n, |at, offset, len| { + let same = |at: usize, offset: usize, len: usize| { + // SAFETY: both are the title's, the one read-only by our hand, the other read by it next. + unsafe { std::slice::from_raw_parts(at as *const u8, len) == std::slice::from_raw_parts(from.add(offset), len) } + }; + in_pieces(to as usize, n, same, |at, offset, len| { // SAFETY: a part of what the title asked for; or the same bytes at // our view of the pages. unsafe { real(at as *mut u8, from.add(offset), len) }; @@ -156,7 +161,11 @@ unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u // SAFETY: the title's, as it asked for it. return unsafe { real(to, byte, n) }; } - in_pieces(to as usize, n, |at, _, len| { + let same = |at: usize, _: usize, len: usize| { + // SAFETY: the title's, read-only by our hand. + unsafe { std::slice::from_raw_parts(at as *const u8, len) }.iter().all(|&there| there == byte as u8) + }; + in_pieces(to as usize, n, same, |at, _, len| { // SAFETY: as in `copied`. unsafe { real(at as *mut u8, byte, len) }; }); @@ -173,7 +182,10 @@ fn overlap(to: usize, from: usize, n: usize) -> bool { /// Does `[to, to + n)` block by block: `put(at, offset, len)` with the /// address to write at, the title's or ours. -fn in_pieces(to: usize, n: usize, put: impl Fn(usize, usize, usize)) { +/// +/// What is there already (`same`, of a part in one guarded block) is not +/// written. +fn in_pieces(to: usize, n: usize, same: impl Fn(usize, usize, usize) -> bool, put: impl Fn(usize, usize, usize)) { const BLOCK: usize = crate::watch::PAGE; add(0); let mut offset = 0; @@ -181,6 +193,11 @@ fn in_pieces(to: usize, n: usize, put: impl Fn(usize, usize, usize)) { let at = to + offset; let len = (BLOCK - at % BLOCK).min(n - offset); if crate::watch::guards_any(at, len) { + if same(at, offset, len) { + add(7); + offset += len; + continue; + } match crate::watch::put_beside(at / BLOCK, 1, |delta| put(at.wrapping_add(delta), offset, len)) { Beside::Done => { add(1); @@ -212,6 +229,84 @@ fn sparse(counts: u64) -> bool { full < 4 || full * 12 < done } +/// Faulting stores by their place in the title's code: the place, and how +/// many left the memory as it was (the low half) or did not (the high one). +static LEARNED: [(AtomicUsize, AtomicU64); 1 << 9] = [const { (AtomicUsize::new(0), AtomicU64::new(0)) }; 1 << 9]; + +/// A store at `rip` would leave the memory as it is, or not. With +/// `VICTORY_WRITE_SITES=`, a place that can be made to look first +/// (`can_look`) and mostly left it is written into that file, for the next +/// start (`victory_loader::write_sites`). +fn learn(rip: usize, same: bool, can_look: bool) { + let slot = &LEARNED[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 55 & 511]; + let there = slot.0.compare_exchange(0, rip, Relaxed, Relaxed).unwrap_or_else(|there| there); + if there != 0 && there != rip { + return; + } + let counts = slot.1.fetch_add(if same { 1 } else { 1 << 32 }, Relaxed); + let (stayed, changed) = (counts & 0xffff_ffff, counts >> 32); + if !same || !can_look || stayed != 256 || changed * 4 > stayed { + return; + } + let Some(file) = std::env::var_os("VICTORY_WRITE_SITES") else { + return; + }; + // (Not here, under a fault of the title's.) + std::thread::spawn(move || { + let Some((image, offset)) = place(rip) else { + return; + }; + use std::io::Write; + let line = format!("{image} {offset:x} or\n"); + let known = std::fs::read_to_string(&file).unwrap_or_default(); + if known.lines().any(|l| l == line.trim_end()) { + return; + } + if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(&file) { + let _ = file.write_all(line.as_bytes()); + } + tracing::info!(image, offset = format_args!("{offset:#x}"), stayed, changed, "a write of the title's that mostly changes nothing, noted"); + }); +} + +/// The file name of the image `address` is in, and where in it. +fn place(address: usize) -> Option<(String, usize)> { + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, GetModuleHandleExW, + }; + const FLAGS: u32 = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; + let mut module = std::ptr::null_mut(); + let mut name = [0u16; 1024]; + // SAFETY: an address, and room for the answers. + let n = unsafe { + if GetModuleHandleExW(FLAGS, address as *const u16, &mut module) == 0 { + return None; + } + GetModuleFileNameW(module, name.as_mut_ptr(), name.len() as u32) + } as usize; + let path = String::from_utf16_lossy(&name[..n]); + let file = path.rsplit(['\\', '/']).next()?.to_owned(); + (!file.is_empty()).then(|| (file, address - module as usize)) +} + +/// The places with the most faulting stores, for the log: offset in its +/// image, how many left the memory as it was, how many did not. +#[cfg(feature = "diagnostics")] +pub(crate) fn busiest() -> String { + let mut all: Vec<(u64, u64, usize)> = LEARNED + .iter() + .map(|(rip, counts)| (counts.load(Relaxed), rip.load(Relaxed))) + .filter(|s| s.1 != 0) + .map(|(counts, rip)| (counts & 0xffff_ffff, counts >> 32, rip)) + .collect(); + all.sort_unstable_by_key(|s| std::cmp::Reverse(s.0 + s.1)); + let of = |&(stayed, changed, rip): &(u64, u64, usize)| { + let (image, offset) = place(rip).unwrap_or_default(); + format!("{}+{offset:x} {stayed}/{changed}", image.chars().skip(14).take(4).collect::()) + }; + all.iter().take(16).map(of).collect::>().join(", ") +} + /// Does the store that faulted at `at`, a byte of a guarded block, beside the /// guards; `false` if it is to open the block (and nothing was done). pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, at: usize) -> bool { @@ -221,13 +316,6 @@ pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug let rip = context.Rip as usize; let site = site(rip); let counts = site.load(Relaxed); - if !sparse(counts) { - // Looked at anew some time. - if site.fetch_add(1 << 32, Relaxed) >> 32 > 4096 { - site.store(0, Relaxed); - } - return false; - } let mut code = [0u8; 15]; // (To the end of the page if the next is not there.) let left = 4096 - rip % 4096; @@ -245,6 +333,23 @@ pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug add(4); return false; } + // SAFETY: a guarded block's, which can be read. + if let Some((same, flags)) = unsafe { store.same(context) } { + learn(rip, same, store.can_look(&code)); + if same && crate::watch::nothing_put(store.at / BLOCK) { + context.EFlags = flags; + context.Rip += store.len as u64; + add(6); + return true; + } + } + if !sparse(counts) { + // Looked at anew some time. + if site.fetch_add(1 << 32, Relaxed) >> 32 > 4096 { + site.store(0, Relaxed); + } + return false; + } let mut done = false; let put = crate::watch::put_beside(store.at / BLOCK, A_STORE, |delta| { // SAFETY: the bytes the title is storing to, at our view of them. diff --git a/crates/victory-gpu/src/titlewrite/decode.rs b/crates/victory-gpu/src/titlewrite/decode.rs index 4c1bd67..e83f5b6 100644 --- a/crates/victory-gpu/src/titlewrite/decode.rs +++ b/crates/victory-gpu/src/titlewrite/decode.rs @@ -382,6 +382,38 @@ unsafe fn change(at: usize, size: usize, locked: bool, f: impl Fn(u64) -> u64) - } impl Store { + /// Whether it leaves the memory as it is, and what it leaves in the flags + /// then; `None` for those of which that is not asked (locked ones, + /// exchanges). + /// + /// # Safety + /// [`Store::size`] bytes can be read at `at`. + pub(super) unsafe fn same(&self, c: &CONTEXT) -> Option<(bool, u32)> { + if self.locked { + return None; + } + let mut there = [0u8; 32]; + // SAFETY: by the caller. + unsafe { std::ptr::copy_nonoverlapping(self.at as *const u8, there.as_mut_ptr(), self.size) }; + match self.op { + Op::Put(bytes) => Some((there[..self.size] == bytes[..self.size], c.EFlags)), + Op::Alu { alu, with, keeps } => { + let was = u64::from_le_bytes(there[..8].try_into().expect("eight bytes")) & mask(self.size); + let (value, flags) = arithmetic(alu, was, with, self.size, keeps, c.EFlags); + Some((value == was, flags)) + } + _ => None, + } + } + + /// Whether the loader can make it look before it writes + /// (`victory_loader::write_sites`): an `or` of a byte with a constant, of + /// the five bytes a jump needs. + pub(super) fn can_look(&self, code: &[u8]) -> bool { + let at = usize::from(code[0] & 0xf0 == 0x40); + self.len >= 5 && code[at] == 0x80 && matches!(self.op, Op::Alu { alu: Alu::Or, .. }) + } + /// Does it, with `to` for the address, and gives the registers what the /// instruction leaves in them (but the instruction pointer). `false`: /// nothing was done. diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 1c790d2..62fb034 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -968,6 +968,15 @@ pub(crate) fn put_beside(block: usize, weight: u32, put: impl FnOnce(usize)) -> Beside::Done } +/// A faulting store of the title's leaves `block` as it is: whether it may be +/// left out (until that has been so often, since the block was taken, that +/// the faults cost more than opening it). +pub(crate) fn nothing_put(block: usize) -> bool { + use std::sync::atomic::Ordering::Relaxed; + let count = put_count(block); + count.load(Relaxed) < crate::titlewrite::MOST && count.fetch_add(1, Relaxed) < crate::titlewrite::MOST +} + /// The title is about to write block by block around `at`: as by a fault. pub(crate) fn opened_for_writing(at: usize) { let mut g = guards(); @@ -3524,6 +3533,15 @@ mod tests { } } assert!(kept > 10, "the guard stayed {kept} times: {:?}", crate::titlewrite::DONE); + // What is there already is not written: nothing to tell. + for k in 0..10 { + // SAFETY (all): as above. + unsafe { ((one + 64) as *mut u32).write_volatile(198) }; + let same = unsafe { std::slice::from_raw_parts((one + BLOCK - 900) as *const u8, 1500) }.to_vec(); + unsafe { copy((one + BLOCK - 900) as *mut u8, same.as_ptr(), same.len()) }; + assert!(!writable(one) && !writable(two), "{k}"); + } + assert_eq!(guard(one, one + SIZE), Some(Vec::new())); // Many stores to a block: it is opened. quiet(); for k in 0..20 { diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs index 3ca43e5..1be130b 100644 --- a/crates/victory-loader/src/console_insn.rs +++ b/crates/victory-loader/src/console_insn.rs @@ -77,7 +77,7 @@ fn patches_clzero() -> bool { } /// `jmp rel32` at `at` to `to`, if it reaches. -fn jump(at: usize, to: usize) -> Option<[u8; 5]> { +pub(crate) fn jump(at: usize, to: usize) -> Option<[u8; 5]> { let rel = i32::try_from(to as i64 - (at as i64 + 5)).ok()?; let [a, b, c, d] = rel.to_le_bytes(); Some([0xe9, a, b, c, d]) @@ -111,10 +111,10 @@ fn clzero_stub(at: usize, stub: usize, cmp: [u8; 3]) -> Option> { /// Room for [`clzero_stub`]s near the title's code: where it is and the bytes used. static STUBS: std::sync::Mutex> = std::sync::Mutex::new(None); -const STUBS_LEN: usize = 64 << 10; +pub(crate) const STUBS_LEN: usize = 64 << 10; /// Memory for code within reach of a `jmp rel32` at `at`. -fn near(at: usize) -> Option { +pub(crate) fn near(at: usize) -> Option { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc}; let at = at & !0xffff; (0x10_0000..0x7000_0000).step_by(0x10_0000).flat_map(|d| [at.checked_sub(d), at.checked_add(d)]).flatten().find_map(|place| { diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 9ae6730..c99eba4 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -38,6 +38,8 @@ mod thunks; #[cfg(windows)] mod tls; #[cfg(windows)] +pub mod write_sites; +#[cfg(windows)] mod windows; #[cfg(windows)] diff --git a/crates/victory-loader/src/write_sites.rs b/crates/victory-loader/src/write_sites.rs new file mode 100644 index 0000000..11f2d97 --- /dev/null +++ b/crates/victory-loader/src/write_sites.rs @@ -0,0 +1,255 @@ +//! Places in the title's code that set a bit of a byte which is nearly always set already, changed +//! at load to look first (`VICTORY_WRITE_SITES=`; off without it). +//! +//! The title's threads raise flags in their objects at every use ("drawn this frame"): `or byte +//! [object+n], bit`. The objects lie in memory that copies for the card are kept of, and each such +//! write was a fault on a guarded page, a copy of its block and a guard again, for a byte that +//! stayed as it was (a fifth of a frame's write faults at one place, run faults-3). Here the +//! instruction becomes a jump to code of ours that reads the byte, leaves the flags the instruction +//! leaves, and runs the instruction only if the byte would change. +//! +//! The places are not ours to know: `victory-gpu` (`titlewrite`) finds them while the title runs, +//! by their faults, and writes them into that file, a line each: the image file's name, the place's +//! offset in it (hexadecimal). Nothing of the title's code is kept. What is not such an instruction +//! is left alone. + +use std::path::Path; + +/// An `or byte [m], constant` at the start of `code`: its length, the bytes that name its address +/// (prefix or 0, ModRM without its register field, what follows up to the constant), the constant. +fn or_byte(code: &[u8]) -> Option<(usize, u8, u8, &[u8], u8)> { + let mut at = 0; + let mut rex = 0; + if code.first()? & 0xf0 == 0x40 { + rex = code[0]; + at = 1; + } + let (&op, &modrm) = (code.get(at)?, code.get(at + 1)?); + if op != 0x80 || modrm >> 3 & 7 != 1 { + return None; + } + let (mode, rm) = (modrm >> 6, modrm & 7); + // Not a register, nor the instruction pointer's neighbourhood. + if mode == 3 || mode == 0 && rm == 5 { + return None; + } + let rest = at + 2; + let mut end = rest; + if rm == 4 { + let sib = *code.get(end)?; + // Not the stack, whose pointer is another in our code; a plain address is left too. + if sib & 7 == 4 && rex & 1 == 0 || sib & 7 == 5 && mode == 0 { + return None; + } + end += 1; + } + end += match mode { + 1 => 1, + 2 => 4, + _ => 0, + }; + let constant = *code.get(end)?; + Some((end + 1, rex, modrm, &code[rest..end], constant)) +} + +/// The code at `stub` for the instruction at `at` (`code` from there). +fn stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + let (len, rex, modrm, rest, constant) = or_byte(code)?; + if len < 5 { + return None; + } + let mut out = vec![0x50, 0x51]; // push rax, push rcx + // movzx eax, byte [m] (the prefix's register field is none of it) + if rex & 0x43 != 0 { + out.push(rex & 0x43); + } + out.extend([0x0f, 0xb6, modrm & 0xc7]); + out.extend(rest); + out.extend([0x89, 0xc1]); // mov ecx, eax + out.extend([0xf7, 0xd1]); // not ecx + out.extend([0x81, 0xe1, constant, 0, 0, 0]); // and ecx, constant: the bits to be set + out.extend([0x0c, constant]); // or al, constant: the flags + let back = |out: &mut Vec| { + let from = stub + out.len(); + out.extend(crate::console_insn::jump(from, at + len)?); + Some(()) + }; + let mut write = vec![0x59, 0x58]; // pop rcx, pop rax + write.extend(&code[..len]); + out.extend([0x67, 0xe3, u8::try_from(write.len() + 5).ok()?]); // jecxz past it + out.extend(write); + back(&mut out)?; + out.extend([0x59, 0x58]); + back(&mut out)?; + Some((len, out)) +} + +/// Changes the places of `list` that are in the image called `name`, mapped at `base` with `size` +/// bytes: how many. +/// +/// # Safety +/// The image stays mapped, and no thread runs its code yet. +pub unsafe fn apply(name: &str, base: usize, size: usize, list: &str) -> usize { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut room: Option<(usize, usize)> = None; + let mut done = 0; + let mut seen = std::collections::BTreeSet::new(); + for line in list.lines() { + let mut words = line.split_whitespace(); + let (Some(image), Some(offset)) = (words.next(), words.next()) else { + continue; + }; + let Ok(offset) = usize::from_str_radix(offset.trim_start_matches("0x"), 16) else { + continue; + }; + if !image.eq_ignore_ascii_case(name) || offset + 16 > size || !seen.insert(offset) { + continue; + } + let at = base + offset; + if room.is_none() { + room = crate::console_insn::near(at).map(|place| (place, 0)); + } + let Some((place, used)) = room.as_mut() else { + return done; + }; + // SAFETY: sixteen bytes inside the image; what is not mapped in it is not named. + let code: [u8; 16] = unsafe { std::ptr::read_unaligned(at as *const _) }; + let to = *place + *used; + let Some((len, body)) = stub(&code, at, to) else { + tracing::warn!(image, offset = format_args!("{offset:#x}"), "not a write of the kind that can be looked at first"); + continue; + }; + let Some(jump) = crate::console_insn::jump(at, to) else { + continue; + }; + if *used + body.len() > crate::console_insn::STUBS_LEN { + return done; + } + let mut old = 0; + // SAFETY: our own code memory, which nothing runs yet; then the instruction, whose page is + // made writable for it and put back, and which nothing runs either. + unsafe { + std::ptr::copy_nonoverlapping(body.as_ptr(), to as *mut u8, body.len()); + if VirtualProtect(at as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + continue; + } + std::ptr::write_bytes(at as *mut u8, 0x90, len); + std::ptr::copy_nonoverlapping(jump.as_ptr(), at as *mut u8, jump.len()); + VirtualProtect(at as *const _, len, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), at as *const _, len); + } + *used += body.len().next_multiple_of(16); + done += 1; + } + done +} + +/// [`apply`] with the file `VICTORY_WRITE_SITES` names. +/// +/// # Safety +/// As [`apply`]. +pub unsafe fn apply_asked(name: &str, base: usize, size: usize) { + let Some(file) = std::env::var_os("VICTORY_WRITE_SITES") else { + return; + }; + let Ok(list) = std::fs::read_to_string(Path::new(&file)) else { + return; + }; + // SAFETY: by the caller. + let places = unsafe { apply(name, base, size, &list) }; + tracing::info!(image = name, places, "writes of the title's that look first (VICTORY_WRITE_SITES)"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn what_can_be_looked_at_first() { + // or byte [r9+9eh], 1 + let (len, rex, modrm, rest, constant) = or_byte(&[0x41, 0x80, 0x89, 0x9e, 0, 0, 0, 1, 0, 0]).unwrap(); + assert_eq!((len, rex, modrm, rest, constant), (8, 0x41, 0x89, &[0x9e, 0, 0, 0][..], 1)); + // or byte [r9+31h], 80h; [rax+rcx*8+5]; [r12+5] (a base of its own) + assert_eq!(or_byte(&[0x41, 0x80, 0x49, 0x31, 0x80]).unwrap().0, 5); + assert_eq!(or_byte(&[0x80, 0x4c, 0xc8, 5, 1]).unwrap().0, 5); + assert_eq!(or_byte(&[0x41, 0x80, 0x4c, 0x24, 5, 1]).unwrap().0, 6); + // Of the stack, beside the instruction, a register's, another operation. + assert!(or_byte(&[0x80, 0x4c, 0x24, 5, 1]).is_none()); + assert!(or_byte(&[0x80, 0x0d, 1, 0, 0, 0, 1]).is_none()); + assert!(or_byte(&[0x80, 0xc9, 1]).is_none()); + assert!(or_byte(&[0x80, 0x61, 5, 1, 0]).is_none()); + } + + /// The instruction in code of a test's, changed, run: the byte, the registers and the flags + /// are what it makes of them unchanged. + #[test] + fn a_changed_write_does_what_it_did() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualProtect}; + type F = unsafe extern "system" fn(*mut u8, *mut [u64; 3]); + for (constant, with) in [(0x80u8, 0x49u8), (1, 0x49), (0x7f, 0x49), (0xff, 0x48), (0x10, 0x49)] { + // mov rax, rcx ; mov r9, rcx ; mov rcx, 1234h ; xor r10, r10 ; or byte [r9+31h | rax+31h], constant ; + // pushfq ; pop r10 ; mov [rdx], r10 ; mov [rdx+8], rax ; mov [rdx+16], rcx ; ret + let mut code = vec![0x48, 0x89, 0xc8, 0x49, 0x89, 0xc9, 0x48, 0xc7, 0xc1, 0x34, 0x12, 0, 0, 0x4d, 0x31, 0xd2]; + let at = code.len(); + if with == 0x49 { + code.extend([0x41, 0x80, 0x49, 0x31, constant]); + } else { + // (With a long address, for the five bytes.) + code.extend([0x80, 0x88, 0x31, 0, 0, 0, constant]); + } + code.extend([0x9c, 0x41, 0x5a, 0x4c, 0x89, 0x12, 0x48, 0x89, 0x42, 0x08, 0x48, 0x89, 0x4a, 0x10, 0xc3]); + // SAFETY: fresh memory for code, twice, one of them changed before it runs. + unsafe { + let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + assert_ne!(place, 0); + std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len()); + let second = place + 0x1000; + std::ptr::copy_nonoverlapping(code.as_ptr(), second as *mut u8, code.len()); + let mut old = 0; + VirtualProtect(second as *const _, 0x1000, PAGE_EXECUTE_READ, &mut old); + let list = format!("other.dll {:x}\nT.dll 0x{at:x}\nt.dll {at:x}\nt.dll 5\nt.dll\n", at); + assert_eq!(apply("t.dll", second, 0x1000, &list), 1); + assert_eq!(std::ptr::read((second + at) as *const u8), 0xe9); + let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); + for was in 0..=255u8 { + let mut bytes = [[0u8; 0x40]; 2]; + bytes[0][0x31] = was; + bytes[1][0x31] = was; + let mut out = [[0u64; 3]; 2]; + plain(bytes[0].as_mut_ptr(), &mut out[0]); + changed(bytes[1].as_mut_ptr(), &mut out[1]); + assert_eq!(bytes[0], bytes[1], "{was:x} | {constant:x}"); + out[0][1] = out[0][1].wrapping_sub(bytes[0].as_ptr() as u64); + out[1][1] = out[1][1].wrapping_sub(bytes[1].as_ptr() as u64); + // (AF is left as it likes.) + out[0][0] &= 0x8c5; + out[1][0] &= 0x8c5; + assert_eq!(out[0], out[1], "{was:x} | {constant:x}"); + } + } + } + } + + /// A byte that would not change is not written. + #[test] + fn a_byte_that_stays_is_not_written() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READONLY, VirtualAlloc, VirtualProtect}; + // mov r9, rcx ; or byte [r9+31h], 80h ; ret + let code = [0x49, 0x89, 0xc9, 0x41, 0x80, 0x49, 0x31, 0x80, 0xc3]; + // SAFETY: fresh memory for code and for a byte, which is read-only when the code runs. + unsafe { + let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len()); + assert_eq!(apply("t.dll", place, 0x10000, "t.dll 3"), 1); + let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8; + data.add(0x31).write(0x83); + let mut old = 0; + VirtualProtect(data.cast(), 4096, PAGE_READONLY, &mut old); + let f: unsafe extern "system" fn(*mut u8) = std::mem::transmute(place); + f(data); + assert_eq!(data.add(0x31).read(), 0x83); + } + } +} From 780f9cc665a254cb00e3c24d23390744d1c6a3f3 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:12:38 -0600 Subject: [PATCH 24/31] VICTORY_PLACED_ORDER is off unless asked for: the case did not come up in three runs Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/card_steps.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 6bd6a5f..b6b99e5 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -85,15 +85,22 @@ pub(super) fn stage() -> u32 { /// Whether a copy at its place in a list ([`place`]) is only in the way of /// what is done on the card in front of the lists if that stands behind it in -/// them (`VICTORY_PLACED_ORDER=0`: wherever it stands, as before), and a -/// submission where it does is cut behind the copy's list ([`cut_for`]). +/// them (`VICTORY_PLACED_ORDER=1`; off: wherever it stands), and a +/// submission where it does is cut behind the copy's list ([`cut_for`]). Off: +/// the case did not come up once in runs submit-1 to submit-3, so it has only +/// its tests behind it. /// /// The fills of constant buffers read the title's ring (7,500 a frame in the /// opening), and one copy of a few hundred bytes a frame writes into it at its /// place in a list. The whole submission was refused for it, and stood 40 to /// 60 ms until the flights had landed (run n19). fn placed_order() -> bool { - crate::toggled!("VICTORY_PLACED_ORDER") + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_PLACED_ORDER") { + return on; + } + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_PLACED_ORDER")) } /// Why [`plan`] refuses for [`place`]. From 158b9aa32979508f9c5b119481ea161795f4ce90 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:21:00 -0600 Subject: [PATCH 25/31] The image's name is kept for VICTORY_WRITE_SITES (the program did not build) Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/run.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 0c7bf46..6706904 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -68,6 +68,7 @@ pub fn run( // and their patched copy are not read again, and were held for the // whole run (two blocks of 114.7 MB each for the title, in // physical memory: run 65's memory map). + let image_name = prepared.file_name(); drop(prepared); drop(original); victory_hle::runtime::set_main_image(image.base()); @@ -163,9 +164,9 @@ pub fn run( let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); show(&exe_name, image.bind_imports(&with_dlls, policy)?); if execute { - let (name, size) = (prepared.file_name(), image.info().size_of_image as usize); + let size = image.info().size_of_image as usize; // SAFETY: the image stays mapped, and nothing of it has run yet. - unsafe { victory_loader::write_sites::apply_asked(&name, image.base(), size) }; + unsafe { victory_loader::write_sites::apply_asked(&image_name, image.base(), size) }; } if !execute { println!("not executing (pass --execute to start the title)"); From 4e995446838615b9a86572382b8d19ee786bb9a2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:31:25 -0600 Subject: [PATCH 26/31] VICTORY_MAP_THREADS=auto is asked for, not the default: 16 threads map no more pages than one in the dorm, and a frame takes longer Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/xmem.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index b34298e..d38c194 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1260,9 +1260,15 @@ fn scatter(wanted: &[(usize, usize)]) -> bool { const GROUP: usize = 64; /// How many threads map a group of pages side by side (`VICTORY_MAP_THREADS`; -/// 1: the caller alone, a page after the other, as before; `auto`, which it -/// is unless set: 1 while mapping takes little of the time, [`WIDE`] while the -/// title streams as fast as its pages are mapped, [`Busy`]). +/// 8 unless set; 1: the caller alone, a page after the other; `auto`: 1 while +/// mapping takes little of the time, [`WIDE`] while the title streams as fast +/// as its pages are mapped, [`Busy`]). +/// +/// shortcut: `auto` is not the default. The intro's diner was there in time +/// with it (one run, textures-d3), but in the dorm, where each call takes 0.3 +/// ms of something that only one at a time gets (until a step of the mission, +/// after which it takes 0.01), 16 threads map no more pages than one, and the +/// groups hold the mapping lock: 260 ms a frame against 125 (textures-d4, -d2). /// /// Mapping and unmapping a view wait for a lock that every protection change /// of a view takes too, and our guards make 100,000 of those a second, from @@ -1289,7 +1295,10 @@ const WIDE: usize = 16; /// `VICTORY_MAP_THREADS` as a number; `None`: by how much there is to map. fn asked_threads() -> Option { static ASKED: LazyLock> = LazyLock::new(|| { - std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).map(|n: usize| n.clamp(1, 32)) + match std::env::var("VICTORY_MAP_THREADS") { + Ok(v) if v.trim() == "auto" => None, + v => Some(v.ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32)), + } }); *ASKED } From c9b3f45ad7ca4364e8d4f6cc2677720e9cf48461 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 13:44:39 -0600 Subject: [PATCH 27/31] The panel is drawn by the diagnostics build only Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2f00206..b65ba97 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8718,6 +8718,7 @@ impl Host { let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; #[cfg(feature = "diagnostics")] let watched = crate::popwatch::take(&self.device, list, texture); + #[cfg(feature = "diagnostics")] p.panel.draw(self, copy, &back, (width, height), format); #[cfg(not(feature = "diagnostics"))] let _ = frame; From f4cc8d8be4880540351d7bea215a51902c4ded02 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 14:01:14 -0600 Subject: [PATCH 28/31] Structure builder: the wait for sizes is off (VICTORY_BVH_SIZES_WAIT=1 turns it on): it mended nothing and costs some 20 ms a frame (light-15) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 12 +++++++++--- docs/fork-ray-tracing.md | 26 +++++++++++++++++--------- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 441990a..b030094 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -797,8 +797,14 @@ impl Memory { const SIZES: usize = usize::MAX - (9 << 33); /// Whether a submission that asks for the sizes of structures is waited for, -/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=0`: it is -/// not). +/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=1`; off). +/// +/// Off: it does not help. In run light-15, with it, 33 of 154 copies had the +/// slot's old size still (all of them recorded one frame after the size was +/// asked for) against 53 of 230 in light-11, 48 of 275 dynamic structures +/// were good, and the title asks in every frame, so every frame waits (109 ms +/// against 90). The title reads the slot before our submission of the asking +/// list is through, or reads it for another purpose; not known. /// /// The title asks for a new structure's compacted size (a program of one /// thread stores it into a small buffer), reads it a frame or two later @@ -810,7 +816,7 @@ const SIZES: usize = usize::MAX - (9 << 33); /// the right size. fn sizes_wait() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_none_or(|v| v != "0")) + *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_some_and(|v| v == "1")) } /// Whether a dispatch of the builder is its program of a structure's size: diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index ec4a1ea..bbca871 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -93,7 +93,8 @@ after it was given them as an unordered access view. |---|---| | `VICTORY_BVH_BUILDER=1` | the builder's stages run | | `VICTORY_BVH_FENCES=0` | no fences around the builder's buffer atomics (beloooo's 72e748ea has them too) | -| `VICTORY_BVH_SIZES_WAIT=0` | submissions that ask for structures' sizes are not waited for | +| `VICTORY_BVH_SIZES_WAIT=1` | submissions that ask for structures' sizes are waited for (off: no help, slow) | +| `VICTORY_BVH_BOUNDS=0` | the builder's accesses are not bounded | | `VICTORY_BVH_TRACE=1` | logs what sizes are asked, when they came, and the copies (diagnostics) | | `VICTORY_BVH_QUARANTINE=1` | nothing it stores comes back to title memory | | `VICTORY_MEMORY_CARD_MB` | the most of it on the card (4096) | @@ -105,17 +106,24 @@ dispatches, faults and what came. ## Known gaps -- Dynamic structures overlap each other (8 of 65 good in run light-10). Cause, - run light-11's trace (`VICTORY_BVH_TRACE=1`): the title asks for a new +- Dynamic structures overlap each other (8 of 65 good in run light-10, 48 of + 275 in light-15). Part of the cause, run light-11's trace (`VICTORY_BVH_TRACE=1`): the title asks for a new structure's compacted size, reads it one or two frames later without looking whether it is there, takes memory of that size and has the structure copied into it. Our submissions land up to two frames late; the title read what the slot held before, another structure's size, and the copy wrote over the - neighbours. A submission that asks is waited for now - (`VICTORY_BVH_SIZES_WAIT=0`: not). -- Some 2,500 pages a frame that are not there are still touched (the notes' - limit): rays in structures that were written over. -- A capture of a frame with the builder on cannot be replayed: the card hangs + neighbours. Waiting for a submission that asks (`VICTORY_BVH_SIZES_WAIT=1`) + did not mend it and costs some 20 ms a frame (light-15): the title asks in + every frame, and what it read was as old as before. Open. +- What a structure that was written over says of its size sent the builder's + copy of it through gigabytes of other structures; bounded now + (`VICTORY_BVH_BOUNDS`). Pages touched that are not there: 2,500 a frame + before, 90 after (the dorm). +- The card's time in the dorm with the builder (timing run light-13, title's + commands 84 ms): `CopyForBVHUpdate` 13.3 ms in 63 dispatches (before the + bound), traces 24 ms (`RaytraceVBuffer` 7.9, screen probes 6.4, irradiance + cache 3.5, primary probes 2.3, shadows 1.6). +- Captures made on 2026-11-25 (builder on or off) hang the card in a replay (cause unknown; do not try). - Five shadow-mask trace programs do not translate (a structure's address out of a descriptor picked from the heap by a computed index: the host would have @@ -150,7 +158,7 @@ fork's constant. | `VICTORY_AMBIENT=` | the estimate, 1 all of it (unset: the title's own) | | `VICTORY_AMBIENT=constant:` | the same light everywhere | | `VICTORY_AMBIENT_SHADE=,` | the creases (1,0.6) | -| `VICTORY_AMBIENT_AIR=` | what the air scatters is bounded by a multiple of the light around (off) | +| `VICTORY_AMBIENT_AIR=` | what the air scatters is bounded by a multiple of the light around (off: the brown veil in the day room stays with it, light-14) | It is off while the builder runs. From c3e643ebbd9070b7ec30c9948cfac8488d662b9f Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 14:01:36 -0600 Subject: [PATCH 29/31] Sets of heap slots are bits, the heaps' records have threads of their own, what is mirrored of them is counted Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 36 +++++++- crates/victory-gpu/src/descriptor/host.rs | 106 ++++++++++++++++++---- crates/victory-gpu/src/draw.rs | 2 +- crates/victory-gpu/src/land.rs | 21 +++-- 4 files changed, 134 insertions(+), 31 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 47f9852..880ba83 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -301,6 +301,7 @@ pub(crate) fn sync_heaps() { } let started = std::time::Instant::now(); let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64); + let mut kinds = [0u64; 6]; let mut page_bytes: Vec = Vec::new(); let mut changed: Vec = Vec::new(); let mut wait: Vec = Vec::new(); @@ -322,7 +323,7 @@ pub(crate) fn sync_heaps() { // since: a shader may pick them by index. let before = host.copied_before(frame); let of_tables = std::sync::atomic::AtomicU64::new(0); - crate::land::each_view(before.len().div_ceil(SYNC_AT_A_TIME), &|n| { + crate::land::each_view(true, before.len().div_ceil(SYNC_AT_A_TIME), &|n| { for &index in before.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { if host.copied_tabled(index, frame) { of_tables.fetch_add(1, Relaxed); @@ -334,6 +335,7 @@ pub(crate) fn sync_heaps() { let of_tables = of_tables.into_inner(); tabled += of_tables; mirrored += before.len() as u64 - of_tables; + kinds[4] += before.len() as u64 - of_tables; // Those of the changed pages, made together at the end. let mut make: Vec = Vec::new(); for (range_from, range_end) in written.take(start as usize, end as usize) { @@ -388,12 +390,22 @@ pub(crate) fn sync_heaps() { } make.push(index); mirrored += 1; + kinds[if heap.samplers() { + 3 + } else if word(0) != VIEW_TAG { + 0 + } else if word(2) >> KIND_SHIFT == 0 { + 1 + } else { + 2 + }] += 1; + kinds[5] += u64::from(!heap.samplers() && host.near_tabled(index, frame)); } } page += crate::watch::PAGE; } } - crate::land::each_view(make.len().div_ceil(SYNC_AT_A_TIME), &|n| { + crate::land::each_view(true, make.len().div_ceil(SYNC_AT_A_TIME), &|n| { for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { host.mirror(index, start + u64::from(index) * step, false); } @@ -407,8 +419,16 @@ pub(crate) fn sync_heaps() { for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) { count.fetch_add(n, Relaxed); } + for (count, n) in SYNCED_KINDS.iter().zip(kinds) { + count.fetch_add(n, Relaxed); + } } +/// Of those mirrored, since the last frame line: no view, a view of an object, +/// another, a sampler; waited and no draw came; next to a slot of a table's. +#[cfg(windows)] +static SYNCED_KINDS: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + /// Records [`sync_heaps`] gives a thread at a time. #[cfg(windows)] const SYNC_AT_A_TIME: usize = 256; @@ -436,20 +456,28 @@ pub(crate) fn sync_line(frames: f64) { ); } let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let kinds = [0, 1, 2, 3, 4, 5].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); if pages == 0 { return; } tracing::info!( "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \ - draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for)", + draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for); of the mirrored \ + {:.0} no views, {:.0} of objects, {:.0} others, {:.0} samplers, {:.0} that waited and no draw came, {:.0} near a table's slot", pages as f64 / frames, looked as f64 / frames, mirrored as f64 / frames, tabled as f64 / frames, later as f64 / frames, micros as f64 / 1000.0 / frames, - waited as f64 / 1000.0 / frames + waited as f64 / 1000.0 / frames, + kinds[0], + kinds[1], + kinds[2], + kinds[3], + kinds[4], + kinds[5] ); } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 53d6f81..1b9118e 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -13,6 +13,65 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; +/// A set of a heap's slots, a bit for each: no lock (a pass that went through +/// a set of 70,000 under its lock kept everyone who writes slots waiting for +/// 5 ms of a frame, timeline thin-6). +struct Slots(Vec); + +impl Slots { + fn new(count: usize) -> Self { + let mut bits = Vec::new(); + bits.resize_with(count.div_ceil(64), Default::default); + Slots(bits) + } + + fn put(&self, slot: u32) { + if let Some(bits) = self.0.get(slot as usize / 64) { + bits.fetch_or(1 << (slot % 64), std::sync::atomic::Ordering::AcqRel); + } + } + + /// Whether it was there. + fn remove(&self, slot: u32) -> bool { + use std::sync::atomic::Ordering::{AcqRel, Acquire}; + let bit = 1 << (slot % 64); + self.0.get(slot as usize / 64).is_some_and(|bits| { + bits.load(Acquire) & bit != 0 && bits.fetch_and(!bit, AcqRel) & bit != 0 + }) + } + + fn of(n: usize, mut bits: u64, out: &mut Vec, which: &impl Fn(u32) -> bool) { + while bits != 0 { + let slot = n as u32 * 64 + bits.trailing_zeros(); + bits &= bits - 1; + if which(slot) { + out.push(slot); + } + } + } + + /// Those that `which` says, in order. + fn all(&self, which: impl Fn(u32) -> bool) -> Vec { + let mut out = Vec::new(); + for (n, bits) in self.0.iter().enumerate() { + Self::of(n, bits.load(std::sync::atomic::Ordering::Acquire), &mut out, &which); + } + out + } + + /// All of them, and none is left. + fn take(&self) -> Vec { + use std::sync::atomic::Ordering::{AcqRel, Acquire}; + let mut out = Vec::new(); + for (n, bits) in self.0.iter().enumerate() { + if bits.load(Acquire) != 0 { + Self::of(n, bits.swap(0, AcqRel), &mut out, &|_| true); + } + } + out + } +} + /// The record each slot of a heap was last made from, and a lock for every /// few hundredth of the slots: whoever makes a slot holds its lock, and no /// other. @@ -123,10 +182,10 @@ pub(crate) struct HostHeap { /// (and its memory a host copy) only when something reads it: a draw /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick /// buffers from the whole heap. - buffers: Mutex>, + buffers: Slots, /// Of those and of the slots that left the set: the ones written since /// [`HostHeap::buffer_changes`] last took them. - changed: Mutex>, + changed: Slots, /// Title slots holding a view of a texture the title may fill itself (a /// placed texture, a texture object), with the frame from which they /// are due: such a texture is uploaded when a draw reads it through a @@ -1487,8 +1546,8 @@ impl HostHeap { free: std::sync::atomic::AtomicU32::new(extra), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), strides, - buffers: Mutex::default(), - changed: Mutex::default(), + buffers: Slots::new(count as usize), + changed: Slots::new(count as usize), textures: Mutex::default(), tabled: (0..if sampler { 0 } else { count }) .map(|_| std::sync::atomic::AtomicU32::new(0)) @@ -2351,22 +2410,19 @@ impl HostHeap { /// The title slots that hold buffer views. pub(crate) fn buffer_slots(&self) -> Vec { - let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); - buffers.iter().copied().collect() + self.buffers.all(|_| true) } /// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every /// slot is in the same part each time. pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec { - let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); - buffers.iter().copied().filter(|slot| slot % parts == part).collect() + self.buffers.all(|slot| slot % parts == part) } /// The title slots whose buffer view was written, or went, since the /// last call. pub(crate) fn buffer_changes(&self) -> Vec { - let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner()); - std::mem::take(&mut *changed).into_iter().collect() + self.changed.take() } /// Records what title slot `index` now holds for shaders that pick @@ -2455,18 +2511,14 @@ impl HostHeap { // dword, either value is one the slot had). unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) }; } - let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); let was = if stride.is_some() { - buffers.insert(index); + self.buffers.put(index); true } else { - buffers.remove(&index) + self.buffers.remove(index) }; if was { - self.changed - .lock() - .unwrap_or_else(|e| e.into_inner()) - .insert(index); + self.changed.put(index); } stale } @@ -2889,6 +2941,13 @@ impl HostHeap { stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES } + /// Whether a slot within 64 of `index` is a table's lately (counted for + /// the log: such a slot is likely one of a table not read yet). + pub(crate) fn near_tabled(&self, index: u32, frame: u64) -> bool { + let first = index & !63; + (first..first + 64).any(|i| i < self.count && self.copied_tabled(i, frame)) + } + /// New records the title copied into slots `slots` in `frame` wait for /// the draw that may read them through a table. pub(crate) fn copied_wait(&self, frame: u64, slots: Vec) { @@ -5267,6 +5326,19 @@ mod tests { assert_eq!(slots(u64::MAX), [2]); } + #[test] + fn a_set_of_slots_holds_what_was_put_in() { + let set = Slots::new(200); + for slot in [199, 0, 64, 63, 130, 64] { + set.put(slot); + } + assert_eq!(set.all(|_| true), [0, 63, 64, 130, 199]); + assert_eq!(set.all(|slot| slot % 2 == 0), [0, 64, 130]); + assert!(set.remove(64) && !set.remove(64) && !set.remove(5)); + assert_eq!(set.take(), [0, 63, 130, 199]); + assert!(set.take().is_empty()); + } + /// A slot a draw read through a table leaves the queue; the title's /// next write of it waits for its draw, and is due after the grace /// frames if none reads it. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index acee146..0dad207 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -806,7 +806,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho const AT_A_TIME: usize = 256; let parts: Vec<&[u32]> = slots.chunks(AT_A_TIME).collect(); let found: Vec>> = parts.iter().map(|_| Default::default()).collect(); - crate::land::each_view(parts.len(), &|n| { + crate::land::each_view(false, parts.len(), &|n| { let looked: Vec<_> = parts[n].iter().map(|&index| (index, look(index))).collect(); // (After each piece while the device lives: a cheap query.) if alive diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 00b3ff1..c6249b7 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -325,15 +325,18 @@ pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) { } /// Calls `f` with every number below `count`, on this thread and on threads -/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 5 with this one; 1: -/// on this one alone). -pub(crate) fn each_view(count: usize, f: &(dyn Fn(usize) + Sync)) { - static POOL: OnceLock<&'static Pool> = OnceLock::new(); - POOL.get_or_init(|| { - let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(5usize); - Pool::new("victory-views", threads.clamp(1, 16)) - }) - .each(count, f); +/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 4 with this one; 1: +/// on this one alone). Those for `records`, the heaps' records copied as +/// bytes, are others than those for the views picked by index: submissions +/// wait for the first, lists for the second, and each kept the other waiting. +pub(crate) fn each_view(records: bool, count: usize, f: &(dyn Fn(usize) + Sync)) { + static POOLS: [OnceLock<&'static Pool>; 2] = [const { OnceLock::new() }; 2]; + POOLS[usize::from(records)] + .get_or_init(|| { + let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4usize); + Pool::new(if records { "victory-records" } else { "victory-views" }, threads.clamp(1, 16)) + }) + .each(count, f); } /// A piece to land: the copy's number, the title address, its bytes. From 95037baf2a302976f94b18e83e5578381e0a8474 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 14:01:37 -0600 Subject: [PATCH 30/31] Revert "Replay: buffers in heaps opened from memory are made again (without the cross-adapter flag)" This reverts commit a50c7fdeb55eca4a27c70151b4154665c32e22e9. --- crates/victory-gpu/src/replay/play.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 887ccc5..fa55c85 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -788,11 +788,7 @@ impl Player { let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64)); *m = (m.0 + 1, m.1 + r.desc.width); } - let mut desc = gpu::to_desc(&r.desc); - // (Heaps are made without what let others open them.) - if matches!(r.place, Place::Placed { .. }) { - desc.Flags &= !D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; - } + let desc = gpu::to_desc(&r.desc); let mut made: Option = None; let clear: Option = r.clear.map(|c| { // SAFETY: 20 bytes that were a clear value. From b6202840aa03d89e841880e056e29d8b96250d5d Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 14:23:12 -0600 Subject: [PATCH 31/31] Title bytes under flights' writes compared with AVX2 on threads of their own, the pairs sent up made on them; helpers that work ahead are not kept on the fast cores VICTORY_UNDER_WIDE=0, VICTORY_UNDER_THREADS (6), VICTORY_FAST_CORES=3 (as before: all of them), VICTORY_WIDE_SPIN= (0: off). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/cores.rs | 11 +- crates/victory-gpu/src/host/send.rs | 26 +- crates/victory-gpu/src/host/traffic.rs | 8 +- crates/victory-gpu/src/land.rs | 17 +- crates/victory-gpu/src/list/thin.rs | 2 +- crates/victory-gpu/src/shadow.rs | 324 +++++++++++++++++++------ 6 files changed, 306 insertions(+), 82 deletions(-) diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs index 436f2f6..4d51fc8 100644 --- a/crates/victory-gpu/src/cores.rs +++ b/crates/victory-gpu/src/cores.rs @@ -39,7 +39,10 @@ fn fast_of(sets: &[(u32, u8)]) -> Vec { } /// `VICTORY_FAST_CORES`: 0: no thread asks; 1: the threads a frame waits for -/// one by one; 2 (the default): the threads they share their work with too. +/// one by one; 2 (the default): the threads they share their work with too; +/// 3: those that work beside the rest as well (lists translated, descriptors +/// made): more threads by then than the fast cores run at a time, while the +/// slow ones stood idle. fn stage() -> u32 { static STAGE: std::sync::OnceLock = std::sync::OnceLock::new(); *STAGE.get_or_init(|| std::env::var("VICTORY_FAST_CORES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2)) @@ -60,6 +63,12 @@ pub(crate) fn keep_helper_on_fast_cores(what: &str) { ask(what, 2); } +/// [`keep_on_fast_cores`] for one of many threads whose work is ahead of what +/// a frame waits for. +pub(crate) fn keep_many_on_fast_cores(what: &str) { + ask(what, 3); +} + fn ask(what: &str, from: u32) { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; if stage() < from { diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 64fc4b7..a397db8 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -186,6 +186,9 @@ pub(super) struct Own { copies: Vec, } +/// Runs whose pairs are one piece of work. +const RUNS_AT_A_TIME: usize = 4096; + /// Takes what `dirty` sends up out of the CPU sides. pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc, Vec<(usize, usize)>)]) -> Option { let began = std::time::Instant::now(); @@ -210,15 +213,29 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc, Vec<(usize, us } let memory = memory(host, at)?; let mut moves: Vec<(usize, usize, usize)> = Vec::new(); + let mut work: Vec<(usize, &[(usize, usize)], usize)> = Vec::new(); for ((shadow, ranges), copy) in dirty.iter().zip(&copies) { let from = shadow.card_data() as usize; moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n))); - let mut to = (memory.data + copy.pairs.0 as usize) as *mut [u32; 2]; + // (80,000 runs of some words a frame: in pieces of work.) + let mut to = memory.data + copy.pairs.0 as usize; + for ranges in ranges.chunks(RUNS_AT_A_TIME) { + let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum(); + if words > 0 { + work.push((from, ranges, to)); + to += words * 8; + } + } + } + let one = |i: usize| { + let (from, ranges, to) = work[i]; + let mut to = to as *mut [u32; 2]; for &(a, b) in ranges.iter().filter(|r| short(r)) { for offset in (a..b).step_by(4) { // SAFETY: inside the copy's mapping (its CPU side, which - // this thread alone writes in these ranges) and inside the - // memory, which has room for every pair. + // the thread that asked, and waits, alone writes in these + // ranges) and inside the memory, which has room for every + // pair, a piece of work's behind the last one's. unsafe { let word = ((from + offset) as *const u32).read_unaligned(); to.write([offset as u32, word]); @@ -226,7 +243,8 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc, Vec<(usize, us } } } - } + }; + crate::land::each_under(work.len(), &one); STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed); STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed); STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed); diff --git a/crates/victory-gpu/src/host/traffic.rs b/crates/victory-gpu/src/host/traffic.rs index 4477164..f74c6ef 100644 --- a/crates/victory-gpu/src/host/traffic.rs +++ b/crates/victory-gpu/src/host/traffic.rs @@ -24,9 +24,15 @@ static MOVED: Mutex>> = Mutex::new(None); pub(super) fn moved(way: usize, span: (u64, u64), ranges: impl Iterator) { let mut all = MOVED.lock().unwrap_or_else(|e| e.into_inner()); let m = all.get_or_insert_with(Default::default).entry(span).or_default(); + // (Thousands of runs lie in one piece, one after the other.) + let mut last = u32::MAX; for (from, to) in ranges.filter(|r| r.0 < r.1) { m.bytes[way] += (to - from) as u64; - m.pieces[way].extend((from >> 16) as u32..=((to - 1) >> 16) as u32); + let (first, end) = ((from >> 16) as u32, ((to - 1) >> 16) as u32); + if (first, end) != (last, last) { + m.pieces[way].extend(first..=end); + } + last = end; } } diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index c6249b7..33a0164 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -238,7 +238,11 @@ impl Pool { for i in 1..threads { // (A helper that is not there is only missed.) let _ = std::thread::Builder::new().name(format!("{name}-{i}")).spawn(move || { - crate::cores::keep_helper_on_fast_cores(name); + if name == "victory-land" { + crate::cores::keep_helper_on_fast_cores(name); + } else { + crate::cores::keep_many_on_fast_cores(name); + } pool.help() }); } @@ -324,6 +328,17 @@ pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) { POOL.get_or_init(|| Pool::new("victory-land", threads())).each(count, f); } +/// [`Pool::each`] on threads kept for the title's bytes under flights' writes +/// (`VICTORY_UNDER_THREADS`, 6 with this one). +pub(crate) fn each_under(count: usize, f: &(dyn Fn(usize) + Sync)) { + static POOL: OnceLock<&'static Pool> = OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::env::var("VICTORY_UNDER_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(6usize); + Pool::new("victory-under", threads.clamp(1, 16)) + }) + .each(count, f); +} + /// Calls `f` with every number below `count`, on this thread and on threads /// kept for making descriptors (`VICTORY_VIEW_THREADS`, 4 with this one; 1: /// on this one alone). Those for `records`, the heaps' records copied as diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index 1991a33..fe9277d 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -303,7 +303,7 @@ fn start() { let threads = std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8usize).clamp(1, 32); for i in 0..threads { let worker = move || { - crate::cores::keep_helper_on_fast_cores("victory-list"); + crate::cores::keep_many_on_fast_cores("victory-list"); crate::queue::no_drain_here(); loop { let recording = { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index cc584c3..f69db8e 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -742,7 +742,7 @@ fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { /// so a piece that held several ranges was hashed once for each. pub(crate) fn joined_piece_runs(mut runs: Vec) -> Vec { runs.sort_unstable_by_key(|r| r.first); - let mut out: Vec = Vec::with_capacity(runs.len()); + let mut out: Vec = Vec::new(); for run in runs { match out.last_mut() { Some(last) if run.first <= last.first + last.pieces => { @@ -1444,6 +1444,25 @@ type Job = Box; struct Workers { jobs: Mutex>, more: std::sync::Condvar, + /// How many jobs there are, for [`spin`]. + there: std::sync::atomic::AtomicUsize, +} + +/// Waits awake until `there` says so, `VICTORY_WIDE_SPIN` microseconds at +/// most (0, the default: not at all): asleep, a thread is woken in 50 us and +/// more, 95 times a frame. +fn spin(there: impl Fn() -> bool) { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| std::env::var("VICTORY_WIDE_SPIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + if most == 0 { + return; + } + let began = std::time::Instant::now(); + while !there() && (began.elapsed().as_micros() as u64) < most { + for _ in 0..16 { + std::hint::spin_loop(); + } + } } /// How many threads are kept for [`wide`]. @@ -1457,6 +1476,7 @@ fn workers() -> &'static Workers { let workers = WORKERS.get_or_init(|| Workers { jobs: Mutex::new(std::collections::VecDeque::new()), more: std::sync::Condvar::new(), + there: std::sync::atomic::AtomicUsize::new(0), }); STARTED.call_once(|| { for i in 0..wide_threads() { @@ -1465,9 +1485,13 @@ fn workers() -> &'static Workers { let workers = WORKERS.get().expect("made above"); loop { let job = { + // A little while awake first: the next work comes + // within microseconds more often than not. + spin(|| workers.there.load(Ordering::Acquire) > 0); let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); loop { if let Some(job) = jobs.pop_front() { + workers.there.fetch_sub(1, Ordering::AcqRel); break job; } jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); @@ -1498,6 +1522,7 @@ fn wide(jobs: Vec) { let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); for job in jobs { let left = left.clone(); + workers.there.fetch_add(1, Ordering::AcqRel); queue.push_back(Box::new(move || { job(); let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); @@ -1512,10 +1537,14 @@ fn wide(jobs: Vec) { loop { let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); match job { - Some(job) => job(), + Some(job) => { + workers.there.fetch_sub(1, Ordering::AcqRel); + job() + } None => break, } } + spin(|| left.0.try_lock().is_ok_and(|n| *n == 0)); let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); while *n > 0 { n = left.1.wait(n).unwrap_or_else(|e| e.into_inner()); @@ -2059,6 +2088,68 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, runs } +/// [`dword_runs`] with no gap, the fast way where it can be: a frame compares +/// 12 MB this way and finds 80,000 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") { + // SAFETY: the processor has AVX2, and the lengths are the same. + return unsafe { word_runs_avx2(title, held) }; + } + dword_runs(at, title, held, 0) +} + +/// # Safety +/// AVX2, and two slices of one length, whole words. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn word_runs_avx2(title: &[u8], held: &[u8]) -> Vec<(usize, usize)> { + use std::arch::x86_64::*; + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut push = |from: usize, len: usize| match runs.last_mut() { + Some((a, n)) if *a + *n == from => *n += len, + _ => runs.push((from, len)), + }; + let n = title.len(); + let mut i = 0; + while i + 256 <= n { + let mut differ = 0u64; + for k in 0..8 { + // SAFETY: inside both slices (`i + 256 <= n`). + let same = unsafe { + _mm256_cmpeq_epi32( + _mm256_loadu_si256(title.as_ptr().add(i + 32 * k).cast()), + _mm256_loadu_si256(held.as_ptr().add(i + 32 * k).cast()), + ) + }; + differ |= u64::from(!_mm256_movemask_ps(_mm256_castsi256_ps(same)) as u8) << (8 * k); + } + while differ != 0 { + let first = differ.trailing_zeros(); + let count = (differ >> first).trailing_ones(); + push(i + 4 * first as usize, 4 * count as usize); + if first + count >= 64 { + break; + } + differ &= u64::MAX << (first + count); + } + i += 256; + } + while i + 4 <= n { + if title[i..i + 4] != held[i..i + 4] { + push(i, 4); + } + i += 4; + } + runs +} + +/// Whether the pages of [`Shadow::merge_under_writes`] are compared on several +/// threads (`VICTORY_UNDER_WIDE=0`: on the submitting one). +fn under_wide() -> bool { + crate::toggled!("VICTORY_UNDER_WIDE") +} + /// What shaders wrote goes into title memory from `at` on: `title` is what /// was read there, `merged` the same with their bytes put in. Only the /// dwords that differ are written. The whole stretch from the first changed @@ -2140,7 +2231,7 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti #[cfg(test)] mod merge_tests { - use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed}; + use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed, word_runs}; /// A piece put back takes the GPU's bytes where the copy changed and /// the title's everywhere else, reads and writes title memory only from @@ -2311,6 +2402,31 @@ mod merge_tests { println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs)); } + #[test] + fn word_runs_are_the_dword_runs() { + let mut seed = 7u32; + let mut random = move || { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + seed >> 8 + }; + for round in 0..200 { + let n = 4 * (random() as usize % 400); + let was: Vec = (0..n).map(|_| random() as u8).collect(); + let mut now = was.clone(); + for _ in 0..random() % 200 { + if n == 0 { + break; + } + let at = random() as usize % n; + let len = (random() as usize % 24).min(n - at); + for b in &mut now[at..at + len] { + *b = random() as u8; + } + } + assert_eq!(word_runs(0x1000, &now, &was), dword_runs(0x1000, &now, &was, 0), "round {round}"); + } + } + #[test] fn changed_runs_are_exactly_the_bytes_that_differ() { let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); @@ -3377,7 +3493,6 @@ impl Shadow { // copy in the PC's memory in the snapshot. let busy = if crate::watch::light() { joined(busy) } else { busy }; let base = start / PAGE; - let mut title = vec![0u8; PAGE]; for (a, e) in busy { // As the refresh itself asks (`update_free`): the journal if // the submission's asking covered the range, else the kernel, @@ -3393,89 +3508,150 @@ impl Shadow { let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); stale_pages_in(base, &copied, a, e, &written) }; - for page in stale { - let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e)); - if lo >= hi { + if stale.is_empty() { + continue; + } + // The lock of the copy's reference (the snapshot, or the + // CPU's side of a copy in the card's memory), from before + // title memory is read until the title's bytes are in: with + // the copy-back on its own thread ([`relay`]) that thread + // puts what the card wrote into title memory and into the + // reference under the same lock, and a page read before + // such a merge and compared after it would take the card's + // bytes for the title's. + let merging = self.merging.write().unwrap_or_else(|e| e.into_inner()); + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let held = if self.card.is_some() { + self.data as usize + } else { + before.as_mut().map_or(0, |snapshot| snapshot.as_mut_ptr() as usize) + }; + if held == 0 { + note_stale(3); + return true; + } + // A page's part in the range, compared and put in: the runs it + // changed; none for a page that is not there (left as it is, and + // looked at again next time) or that had too many. + type Done = Option>; + let left = std::sync::atomic::AtomicI64::new(*runs_left as i64); + let over = std::sync::atomic::AtomicBool::new(false); + let done: Vec> = stale.iter().map(|_| Mutex::new(None)).collect(); + let page_of = |i: usize| -> (usize, usize) { ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e)) }; + let one = |i: usize| { + let (lo, hi) = page_of(i); + if lo < hi && !over.load(Ordering::Relaxed) { + // SAFETY: the reference holds the copy's bytes at the + // copy's offsets, and these are in a declared range; the + // locks held above keep out what else writes them, and + // no two pages are the same. + let runs = unsafe { self.merge_page_under_writes(lo, hi - lo, held as *mut u8, &left) }; + match runs { + Ok(runs) => *done[i].lock().unwrap_or_else(|e| e.into_inner()) = runs, + Err(()) => over.store(true, Ordering::Relaxed), + } + } + }; + // (Not on the threads of `wide`: the thread that waits there + // takes whatever work comes, and a landing's takes the lock.) + if stale.len() > 2 && under_wide() { + crate::land::each_under(stale.len(), &one); + } else { + (0..stale.len()).for_each(one); + } + *runs_left = left.into_inner().max(0) as usize; + let mut taken = Vec::new(); + for (i, runs) in done.into_iter().enumerate() { + let Some(runs) = runs.into_inner().unwrap_or_else(|e| e.into_inner()) else { continue; - } - let n = hi - lo; - let title = &mut title[..n]; - // The lock of the copy's reference (the snapshot, or the - // CPU's side of a copy in the card's memory), from before - // title memory is read until the title's bytes are in: with - // the copy-back on its own thread ([`relay`]) that thread - // puts what the card wrote into title memory and into the - // reference under the same lock, and a page read before - // such a merge and compared after it would take the card's - // bytes for the title's. - let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner()); - let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - // A page that is not there is left as it is, and looked at - // again next time. - if !crate::host::read_into(lo as *const u8, title) { - continue; - } - MERGED[0].fetch_add(1, Ordering::Relaxed); - let at = lo - start; - if self.card.is_some() { - // SAFETY: inside the mapping of the copy's CPU side, - // which only the submitting thread writes. - let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - // Whole words go up as pairs, all of them in one - // dispatch: only what is a copy of its own counts. - let runs = if crate::host::words_under() { dword_runs(lo, title, held, 0) } else { changed_runs(title, held) }; - let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m); - let copies = runs.iter().filter(own).count(); - if copies > *runs_left { - note_stale(2); - return true; - } - *runs_left -= copies; - let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec()); - for &(r, m) in &runs { - held[r..r + m].copy_from_slice(&title[r..r + m]); - MERGED[2].fetch_add(m as u64, Ordering::Relaxed); - } - MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed); - self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m))); - if let Some(was) = was { - crate::host::upcheck::note(self.id, at, &was, held); - } - } else { - let Some(snapshot) = before.as_mut() else { - note_stale(3); - return true; - }; - // SAFETY: the snapshot's allocation holds the copy's - // bytes at the copy's offsets (`writing`), and these - // are in a declared range. - let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) }; - for (r, m) in changed_runs(title, held) { - // SAFETY: inside the copy's mapping. The card may be - // writing the copy beside these bytes; they are - // written here and nothing around them. - unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; - held[r..r + m].copy_from_slice(&title[r..r + m]); - MERGED[1].fetch_add(1, Ordering::Relaxed); - MERGED[2].fetch_add(m as u64, Ordering::Relaxed); - } - } - drop(before); - drop(_merging); + }; + let (lo, hi) = ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e)); + MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed); + MERGED[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); + self.card_changed_runs(runs.into_iter().map(|(r, m)| (lo - start + r, lo - start + r + m))); // Taken, if the range holds all of the page that is in the // copy; else the rest of it is the refresh's, which notes // only whole pages, and the page is looked at again. - if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e { - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if lo < hi && (stale[i] * PAGE).max(start) >= a && ((stale[i] + 1) * PAGE).min(end) <= e { + taken.push(stale[i]); + } + } + drop(before); + drop(merging); + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + for page in taken { if let Some(at) = copied.get_mut(page - base) { *at = now; } } } + if over.into_inner() { + note_stale(2); + return true; + } } false } + /// Of [`Shadow::merge_under_writes`]: title memory `[lo, lo + n)`, in one + /// page, compared with the reference, which begins at `held`, and put in. + /// The runs that changed, none if it cannot be read, and an error if + /// there were more to copy one by one than `left`. + /// + /// # Safety + /// The reference holds the copy's length, and nothing else writes these + /// bytes of it during the call. + unsafe fn merge_page_under_writes( + &self, + lo: usize, + n: usize, + held: *mut u8, + left: &std::sync::atomic::AtomicI64, + ) -> Result>, ()> { + thread_local! { + static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + TITLE.with_borrow_mut(|title| { + title.resize(PAGE, 0); + let title = &mut title[..n]; + if !crate::host::read_into(lo as *const u8, title) { + return Ok(None); + } + MERGED[0].fetch_add(1, Ordering::Relaxed); + let at = lo - self.start as usize; + // SAFETY: the caller's. + let held = unsafe { std::slice::from_raw_parts_mut(held.add(at), n) }; + if self.card.is_some() { + // Whole words go up as pairs, all of them in one + // dispatch: only what is a copy of its own counts. + let runs = if crate::host::words_under() { word_runs(lo, title, held) } else { changed_runs(title, held) }; + let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m); + let copies = runs.iter().filter(own).count() as i64; + if copies > 0 && left.fetch_sub(copies, Ordering::Relaxed) < copies { + return Err(()); + } + let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec()); + for &(r, m) in &runs { + held[r..r + m].copy_from_slice(&title[r..r + m]); + } + if let Some(was) = was { + crate::host::upcheck::note(self.id, at, &was, held); + } + return Ok(Some(runs)); + } + let runs = changed_runs(title, held); + for &(r, m) in &runs { + // SAFETY: inside the copy's mapping. The card may be + // writing the copy beside these bytes; they are + // written here and nothing around them. + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; + held[r..r + m].copy_from_slice(&title[r..r + m]); + } + Ok(Some(runs)) + }) + } + /// At submission: copies what changed of `[address, address + len)` /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied.